[英]how can i find only the full word and not just part of it in regex?
[英]Find full word by part of it using regex
我有一部分单词,应该使用正则表达式在字符串中找到完整的单词。 例如,我有以下文本:
If it bothers you, call it a "const identifier" instead.
It doesn't matter whether you call max a const variable or a const identififfiieer. What matters...
单词的一部分: identifi
。 我必须同时找到: identifier
和identififfiieer
。
我尝试了以下正则表达式(javascript):
[\ ,!@#$%^&*()\.\"]*(identifi.*?)[\ ,!@#$%^&*()\d\.\"]
因此,它会搜索被标点符号或空格包围的单词部分。 有时这个正则表达式可以正常工作,但在这种情况下,它还包括引号和点对匹配。 它出什么问题了? 也许有更好的主意?
您可以使用
\bidentifi.*?\b
意思是:
'foo "bar identifier"'.match(/\bidentifi.*?\b/g); // ["identifier"]
'foo identififfiieer. bar'.match(/\bidentifi.*?\b/g); // ["identififfiieer"]
您可以使用\\w*identifi\\w*
\\w
代表“文字字符”。 它始终与ASCII字符[A-Za-z0-9_]
匹配。 请注意包含下划线和数字。
这是一个演示,展示了正则表达式及其匹配项。
附带说明一下,如果使用捕获组,则原始正则表达式实际上可以正常工作:
var body = 'If it bothers you, call it a "const identifier" instead.\nIt doesn\'t matter whether you call max a const variable or a const identififfiieer. What matters...';
var reg = /[\ ,!@#$%^&*()\.\"]*(identifi.*?)[\ ,!@#$%^&*()\d\.\"]/g;
var match;
while (match = reg.exec(body)) {
console.log('>' + match[1] + '<');
}
输出:
>identifier<
>identififfiieer<
这是此代码的演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.