[英]Multiple Regex Matches Using Negative LookAhead
I'm trying to match the word "query" in the given string "The query resolution with this query management should not get highlighted. Only this query should get highlighted. " 我试图匹配给定字符串“查询”中的单词“查询”,该查询管理的查询分辨率不应突出显示。仅此查询应突出显示。”
using the following regex: 使用以下正则表达式:
(query(?!\smanagement)|query(?!\sresolution))
But I'm unable to get the regex to match only the last word "query" in the string. 但是我无法使正则表达式仅匹配字符串中的最后一个单词“ query”。
Regards, 问候,
Alok 阿洛克
You (query(?!\\smanagement)|query(?!\\sresolution))
regex fails to match only one query
and matches all the 3 query
s because you have two alternatives: query
that should not be followed with a space and management
and another alternative matching a query
that is not followed with a space and resolution
. 您
(query(?!\\smanagement)|query(?!\\sresolution))
regex只能匹配一个query
而不能匹配所有3个query
因为您有两种选择:不应该跟空格和management
query
,以及另一个匹配不带空格和resolution
的query
替代方法。 You need to use one lookahead that will disallow both resolution
AND management
. 您需要使用一个先行记录,这将不允许同时进行
resolution
和management
。
You can use 您可以使用
query(?!\s(?:management|resolution))
The lookahead (?!\\s(?:management|resolution))
will fail the match of query
that is followed with 1 whitespace followed with either management
or resolution
. 前瞻
(?!\\s(?:management|resolution))
将使query
的匹配失败,该query
后跟1个空格,后跟management
或resolution
。
To only match whole words, use \\b
: 要只匹配整个单词,请使用
\\b
:
\bquery\b(?!\s\b(?:management|resolution)\b)
Python demo showing how you can get the first match in a string with this regex with re.search
: Python演示显示了如何使用
re.search
使用此正则表达式获取字符串中的第一个匹配项:
import re
p = re.compile(r'query(?!\s*(?:management|resolution))')
test_str = "The query resolution with this query management should not get highlighted. Only this query should get highlighted.The query resolution with this query management should not get highlighted. Only this query should get highlighted."
m = p.search(test_str)
if m:
print(m.group())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.