[英]Python regex to search substring in multiline string variable
I am trying to search for group of words in a multiline string variable.我正在尝试在多行字符串变量中搜索一组单词。 I can do this by我可以这样做
>>> test_1 = """--Comment
... /*Comment*/
... MERGE fhkjfsk lkfjs;lfks;f
... hdkjdkd
... fjlkf
... """
>>> m = re.search(r"(insert|merge|update|delete)\s*", test_1, re.IGNORECASE)
>>> print(m)
<_sre.SRE_Match object; span=(22, 28), match='MERGE '>
But I want to match only those words that are present in a line that doesn't start with "--" or "/*".但我只想匹配那些不以“--”或“/*”开头的行中的单词。 So I don't want following to match:所以我不希望以下匹配:
>>> test_1 = """--Comment
... /*Comment*/
... --MERGE fhkjfsk lkfjs;lfks;f
... hdkjdkd
... fjlkf
... """
>>> m = re.search(r"(insert|merge|update|delete)\s*", test_1, re.IGNORECASE)
>>> print(m)
<_sre.SRE_Match object; span=(24, 30), match='MERGE '>
This is what I am unable to get to work.这就是我无法上班的原因。 I have tried:我努力了:
>>> test_1 = """--Comment
... /*Comment*/
... --MERGE fhkjfsk lkfjs;lfks;f
... INSERT fhskjfsf
... gfdsjhs
... """
>>> m = re.search(r"^(?!--)(insert|merge|update|delete)\s*", test_1, re.IGNORECASE)
>>> print(m)
None
>>>
I think I need something in between the two parenthesis (?!--)(insert|merge|update|delete)
and have tried adding我想我需要两个括号之间的东西(?!--)(insert|merge|update|delete)
并尝试添加
.+ like (?!--).+(insert|merge|update|delete)
.+ 喜欢(?!--).+(insert|merge|update|delete)
\s* like (?!--)\s*(insert|merge|update|delete)
\s* 喜欢(?!--)\s*(insert|merge|update|delete)
. . like (?!--).(insert|merge|update|delete)
像(?!--).(insert|merge|update|delete)
.* like (?!--).*(insert|merge|update|delete)
but it doesn't help. .* 喜欢(?!--).*(insert|merge|update|delete)
但它没有帮助。
Any suggestions on how to get this working would be greatly appreciated.任何有关如何使这项工作的建议将不胜感激。
The regex is fine, but the ^
matches only the start of the whole string.正则表达式很好,但^
仅匹配整个字符串的开头。 You should use re.MULTILINE
to make it match starts of lines.您应该使用re.MULTILINE
使其匹配行的开头。
re.search(r"^(?!--)(insert|merge|update|delete)\s*", test_1, re.IGNORECASE | re.MULTILINE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.