简体   繁体   English

RegEx匹配整个单词

[英]RegEx match entire word

I am trying to catch all words that contains " centimeters ", like: 10.50centimeters from this sentence " This product have 10.50centimeters length.. ". 我试图捕捉所有包含“ 厘米 ”的单词,例如: 10.50centimeters from this sentence“ 此产品有10.50厘米长... ”。

my function: 我的功能:

function findMatchingWords(t, s) {
    var re = new RegExp("\\w*"+s+"\\w*", "g");
    return t.match(re);
}
findMatchingWords('This product have 10.50centimeters length..','centimeters');

but returns only " 50centimeters ". 但只返回“ 50centimeters ”。 Is not getting the numbers before the dot. 没有得到点之前的数字。

Any help with this please? 有什么帮助吗?

Is not getting the numbers before the dot. 没有得到点之前的数字。

\\w doesn't match a dot, it's equivalent to [A-Za-z0-9_] . \\w与点不匹配,相当于[A-Za-z0-9_] [\\w.] would (or [A-Za-z0-9_.] ). [\\w.]会(或[A-Za-z0-9_.] )。

var re = new RegExp("[\\w.]*"+s+"\\w*", "g");

Live Example: 实例:

 function findMatchingWords(t, s) { var re = new RegExp("[\\\\w.]*"+s+"\\\\w*", "g"); return t.match(re); } console.log(findMatchingWords('This product have 10.50centimeters length..','centimeters')); 


Side note: You'll want to escape characters with special meaning in s before feeding it to the RegExp constructor. 旁注:在将它提供给RegExp构造函数之前,您需要在s转义具有特殊含义的字符。 This question's answers have functions to do that. 这个问题的答案有功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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