繁体   English   中英

正则表达式在单引号之间查找内容,但前提是包含某个单词

[英]Regex find content in between single quotes, but only if contains certain word

我想获取单引号之间的内容,但前提是它包含某个单词(即'sample_2')。 它还不应与带有空格的匹配。

输入示例:(以下应匹配并仅返回: ../sample_2/filesample_2/file

['asdf', '../sample_2/file', 'sample_2/file', 'example with space', sample_2, sample]

现在我刚刚匹配了列表中的前 3 个项目:

'(.\S*?)' 

我似乎找不到正确的正则表达式来返回那些包含单词“sample_2”的正则表达式

如果您想要特定的单词/字符,您需要将它们放在正则表达式中,而不是使用 '\S'。 \S 相当于[^\r\n\t\f\v ]或“任何非空白字符”。

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' 的字符串也不需要双转义 '\' 字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM