繁体   English   中英

使用正则表达式查找完整单词的一部分

[英]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 我必须同时找到: identifieridentififfiieer

我尝试了以下正则表达式(javascript):

[\ ,!@#$%^&*()\.\"]*(identifi.*?)[\ ,!@#$%^&*()\d\.\"]

因此,它会搜索被标点符号或空格包围的单词部分。 有时这个正则表达式可以正常工作,但在这种情况下,它还包括引号和点对匹配。 它出什么问题了? 也许有更好的主意?

您可以使用

\bidentifi.*?\b

意思是:

  • 在单词边界处声明位置
  • 从字面上匹配字符“ identifi”
  • 匹配任何不是换行符的单个字符
    • 在0到无限制的时间之间,尽可能少的时间,根据需要扩展(延迟)
  • 在单词边界处声明位置
'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.

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