我想获取单引号之间的内容,但前提是它包含某个单词(即"sample_2"(。 此外,它不应与带有空格的匹配。
输入示例:(以下内容应仅匹配并返回:../sample_2/file
和sample_2/file
(
['asdf', '../sample_2/file', 'sample_2/file', 'example with space', sample_2, sample]
现在我只有与列表中的前 3 个项目匹配的项目:
'(.S*?)'
我似乎找不到正确的正则表达式来返回包含单词"sample_2"的正则表达式
如果你想要特定的单词/字符,你需要将它们放在正则表达式中,而不是使用'\S'。 \S 等效于[^rntfv ]
或"任何非空格字符"。
import re
teststr = "['asdf', '../sample_2/file', 'sample_2/file', 'sample_2 with spaces','example with space', sample_2, sample]"
matches = re.findall(r"'([^s']*sample_2[^s]*?)',", teststr)
# ['../sample_2/file', 'sample_2/file']
根据您的措辞,您建议所需的单词可以更改。 在这种情况下,我建议使用 re.compile(( 动态创建一个字符串,然后定义正则表达式。
import re
word = 'sample_2'
teststr = "['asdf', '../sample_2/file', 'sample_2/file', ' sample_2 with spaces','example with space', sample_2, sample]"
regex = re.compile("'([^'\s]*"+word+"[^\s]*?)',")
matches = regex.findall(teststr)
# ['../sample_2/file', 'sample_2/file']
另外,如果您还没有听说过此工具,请查看 regex101.com。 我总是在这里构建我的正则表达式,以确保它们正确。 它为您提供参考,正在发生的事情的解释,甚至允许您在浏览器中对其进行测试。
正则表达式的解释
regex = r"'([^s']*sample_2[^s]*?)',"
找到第一个撇号,开始组捕获。捕获除空格字符或相应的结尾撇号之外的任何内容。 在接受任何非空格字符之前,它必须看到字母"sample_2"。 当您看到右撇号和逗号时停止组捕获。
注意:在python中,带有字符"r"的字符串"或"表示文本被编译为正则表达式。 带有字符"r"的字符串也不需要双转义"\"字符。