[英]Regular Expression word matching
I am trying to match a word in a string using \\b
我正在尝试使用\\b
匹配字符串中的单词
For example 例如
I want to match the word abcde
in the string xyz abcde ddd
and xyz abcde.html ddd
. 我想在字符串xyz abcde ddd
和xyz abcde.html ddd
匹配单词abcde
。 I am using a regular expression \\babcde\\b
and what I want is to match only the first string but not the second since it contain abcde.html
. 我正在使用正则表达式\\babcde\\b
,我想要的是仅匹配第一个字符串而不匹配第二个字符串,因为它包含abcde.html
。 But this regex matches both of them. 但是此正则表达式与它们都匹配。
How can I achieve the result I want? 如何获得想要的结果?
You can use a negative look-ahead to avoid matching any abcde
followed by a period and alphanumerics: 您可以使用负数abcde
以避免匹配任何abcde
后跟句号和字母数字:
\babcde\b(?!\.\w+)
The (?!\\.\\w+)
negative look-ahead makes checks, but does not cosume the presence of the period and alphanumerics, and if they are present, no match is returned. 否定的(?!\\.\\w+)
预检查,但不假定是否存在句点和字母数字,如果存在,则不返回任何匹配项。 You can make it more generic by replacing \\w+
with \\S+
(1 or more non-whitespace characters). 通过将\\w+
替换为\\S+
(1个或多个非空白字符),可以使其更通用。
\\babcde(?=.*?\\b) a look ahead is what you need. \\ babcde(?=。*?\\ b)向前看是您所需要的。 I'll do up an example with a test link in a moment. 我稍后将用一个测试链接来完成一个示例。
update: http://refiddle.com/2ing 更新: http : //refiddle.com/2ing
edit: if by "second string" you mean the ".html" part then this answer will work. 编辑:如果用“第二个字符串”表示“ .html”部分,则此答案有效。 but if you meant the whole second string of "xyz abcde.html ddd" then stribizhev has the right answer. 但是,如果您要说的是“ xyz abcde.html ddd”的第二个字符串,那么stribizhev的答案正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.