正则表达式提取与给定模式中的位置匹配的子字符串

时间:2019-04-04 15:08:40

标签: python regex string

我有一系列模板字符串,它们定义了{}的变量替换。并且替换可以采用任何字符,但是周围的字符串是固定的。

# template string pattern
file{a}-{b}stuff.txt 

# final string after substitution
fileDR-v1.0stuff.txt

给出一个示例字符串,我希望能够提取出哪些部分是已被替换的变量。例如,给定“ fileDR-v1.0stuff.txt”,它应返回{'a':'DR','b':'v1.0'}。通过使用正则表达式组(。*)替换所有带括号的内容以捕获所有字符,可以在模板之外创建正则表达式模式,从而使它最有效。

template = "file{a}-{b}stuff.txt"
example = "fileDR-v1.0stuff.txt"

# escape any periods in the pattern
subtemp = template.replace('.','\.')
# create the regex pattern
pattern = re.sub('{(.*?)}', '(.*)', subtemp)
print(pattern)
'file(.*)-(.*)stuff.txt'

# perform the search using the pattern on both the template and example 
pmatch = re.search(pattern, template)
tmatch = re.search(pattern, example)

pmatch.groups()
('{a}', '{b}')

tmatch.groups()
('DR', 'v1.0')

从这些组中,我可以提取键和值并重新创建a ='DR',b ='v1.0'的映射。但是,我在提取带有背对背括号的模板的正确字符串时遇到问题。是否有正确的语法来处理这些极端情况?

我拥有的示例模板

'{a}.{b}'
'{dr}Q/{dr}Q.fits'  
'parts_{dr}{version}_{sample}_{ns}.fits.gz'
'path/{ver}/{plate}/stack/file-{plate}-{ifu}-LOG.fits.gz'

示例字符串

'mask.html'
'DR10Q/DR10Q.fits'
'parts_DR12v1.0_1_n.fits.gz'
'path/v2_4_3/8000/stack/file-8000-191-LOG.fits.gz'

我当前的(。*)和转义.的模式适用于大多数情况。如果我对这四个示例运行上面的代码,我将得到

('{a}', '{b}')
('mask', 'html')
---- 
('{dr}', '{dr}')
('DR10', 'DR10')
----
('{dr}{version}', '', '{sample}', '{ns}')
('DR12v1.0', '', '1', 'n')
----
('{ver}', '{plate}', '{plate}', '{ifu}')
('v2_4_3', '8000', '8000', '191')
----

处理{dr}{version}{a}{b}之类的案件的最佳方法是什么?我知道regex没有真正的方法可以将两个字符串分开,但是还有其他选择吗?

0 个答案:

没有答案