[英]How to "match if there is one occurrence but don't match if the pattern appears multiple times" in regular expression
[英]Regular expression to match repeated occurrence of a pattern
我有一些可能的输入字符串,如下所示:
Roll|N/A|300x60|(1x1)|AAA|BBB
Desktop|1x1|(1x1)|AAA|BBB
Desktop|NA|(NA)|AAA|BBB
Roll|N/A|N/A|(1x1)|AAA|BBB
从中,我试图检测\\d+x\\d+
类型的模式(例如,第一行的'300x60','1x1';第二行的'1x1','1x1';第三行的None
;以及最后一个为“ 1x1”)。 有人可以告诉我如何编写Python正则表达式搜索以在给定的字符串中不捕获这种模式的一个或多个或多个出现的情况吗? 我已经在下面尝试过,它只捕获给定句子中模式的第一次出现或第二次出现。 谢谢!
r = re.search('(\(?\d+x\d+\)?)+', my_str)
r.group() # only gives me '320x50' for the first input above
您可以使用
import re
my_strs = ["Roll|N/A|300x60|(1x1)|AAA|BBB", "Desktop|1x1|(1x1)|AAA|BBB", "Desktop|NA|(NA)|AAA|BBB", "Roll|N/A|N/A|(1x1)|AAA|BBB"]
print([re.findall(r'\d+x\d+', s) for s in my_strs])
# => [['300x60', '1x1'], ['1x1', '1x1'], [], ['1x1']]
要点是使用re.findall
将获取多个匹配项(或捕获的子字符串,但我建议的模式中没有捕获组)。 您遇到的问题是您试图用1次搜索操作来匹配重复的捕获 。 由于子字符串不相邻,不固定,因此只有一个结果。
您可以这样:
import re
input_strings = ['Roll|N/A|300x60|(1x1)|AAA|BBB', 'Desktop|1x1|(1x1)|AAA|BBB',\
'Desktop|NA|(NA)|AAA|BBB','Roll|N/A|N/A|(1x1)|AAA|BBB']
print [[ j if j else None for j in [re.findall('(\d+x\d+)', i)] ][0] for i in input_strings ]
输出:
[['300x60', '1x1'], ['1x1', '1x1'], None, ['1x1']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.