有没有更简单的方法来检查字符串是否与特定模式匹配并从该模式中检索组?
我想浏览一个带有 {readlines} 的文件,并收集引号之间有内容的任何行:
**{**
**"simpleSelectors": [**
"*",**
如果这些是我文件中的行,我的列表中应该有['simpleSelectors','*']
regexline = re.compile('"(.*)"')
for i in css:
if re.search(regexline, i):
x = re.search(regexline, i)
inputs.append(x.group(1))
你不需要遍历每一行。并且无需转义正则表达式中的引号:
import re
css='{nn"simpleSelectors": [nn"*",'
inputs = []
regexline = re.compile('"(.*)"')
matches = re.findall(regexline, css)
print( matches) # ['simpleSelectors', '*']
编辑:要细分您的匹配项,请使用
matches = [item for match in re.findall(regexline, css) for item in match.split()]
您可以使用以下方法在所有行上使用 re.findall:
matches = re.findall(regexline, css)