簡體   English   中英

解析字符串模式-Python

[英]Parsing a string pattern - Python

我在以下模式中有一個字符串模式(用於xml測試報告程序):

'testsets.testcases.[testset].[testcase]-[date-stamp]'

例如:

a='testsets.testcases.test_different_blob_sizes.TestDifferentBlobSizes-20150430130436'

我知道我總是可以通過執行以下操作來解析testcase testsettestcase名稱:

temp = a.split("-")[0]
current = temp.split(".")
testset = '.'.join(current[:-1]) + ".py"
testcase = current[-1]

但是,我想使用一種更Python的方式來實現這一點,例如regex或我將在一行中完成的任何其他表達式。 我該怎么做?

你可以試試:

testset, testcase = re.search('(.*)\.(.*)-.*', a).group(1, 2)
testset += '.py'

re.search在匹配MatchObject上返回MatchObject ,它具有一個group方法,可用於為正則表達式(正則表達式中的“()”)提取匹配組。

只需使用groups ,從正則表達式搜索組獲得:

data = re.search(r'.+\..+\.(.+)\.(.+)-(\d+)', string).groups()

如您在問題的第一部分中一樣,如果嚴格要提取測試集和測試用例,即“ test_different_blob_sizes”和“ TestDifferentBlobSizes”,則可以執行以下操作:

testset, testcase = re.split('[.-]',s)[2:4]

有關基於所擁有內容的緊湊型正則表達式代碼的信息,請參見Ziyao Wei的回復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM