如何在python中使用regex从字符串中获取特定数据

时间:2014-05-30 08:07:55

标签: regex

我有以下程序想要获取

“计划”,“非自动化”,“st3reporter”,“功能”,“报告至3次 - 每2小时”,“st3-throttling-cdb”

**来自字符串**的这些值

import re
string='''
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ReportUpToTimesEveryHours {

        String objective = "04 - Report up to 3 times every 2 hours";
        String testName = "ReportUpToTimesEveryHours";

@BeforeMethod(alwaysRun = true)
public void beforeMethod() {
        logger.info(Constants.LOGGER_SEPERATOR);
        logger.info("Start -- " + testName + " - " + objective);

}

                        @Test(groups = { "planned", "not automated", "st3reporter", "functional", "report-upto3times-per2hrs", "st3-throttling-cdb" },
        description = "04 - Report up to 3 times every 2 hours")
public void testReportUpToTimesEveryHours() {

}

@AfterMethod(alwaysRun = true)
public void afterMethod() {
        logger.info("End -- " + testName + " - " + objective);
        logger.info(Constants.LOGGER_SEPERATOR);
}

}
'''
pattern=re.compile(r' (\@Test\(groups\s*=\s*\{)')
m= pattern.search(string)
print m.group()

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

pattern=re.compile(r' @Test\(groups\s*=\s*\{([^\}]+)')
result_set = [i.strip() for i in 
              pattern.search(string).group(1).replace('"', '').split(',')] 

该值将存储一个列表:

['planned', 'not automated', 'st3reporter', 'functional', 'report-upto3times-per2hrs', 'st3-throttling-cdb']