简体   繁体   English

正则表达式单词匹配

[英]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 dddxyz 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+)

See demo 观看演示

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个或多个非空白字符),可以使其更通用。

You can also use a positive look-ahead 您也可以使用积极的前瞻性

\babcde\b(?=\s)

Demo here 在这里演示

The (?=\\s) check any white space character [\\r\\n\\t\\f ] after babcde (?=\\s)babcde之后检查任何空白字符[\\r\\n\\t\\f ]

\\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.

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