繁体   English   中英

正则表达式匹配多个单词的变体

[英]regex match variations of multiple words

我已经将我的值存储在一个变量中:

var myvalue = "hello bye";
var myText = "hellobye is here and hello-bye here and hello.bye"

如何检查myvalue的变体是否出现在文本中?
我正在使用这种模式:

hello[-. ]*?bye

但是我不能破坏我这样的变量值。 还有一件事,如果我的值包含两个以上的元素怎么办? hello bye hi

您可以用[-.\\\\s]*?替换所有空白块(仅用/\\s+/g匹配它们) [-.\\\\s]*? 创建一个正则表达式以匹配myvalue的变体:

 var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" console.log(myText.match(new RegExp(myvalue.replace(/\\s+/g, '[-.\\\\s]*?'), 'g'))); 

我认为您追求的是这样的事情。 如果您需要解释,请发表评论,我会尽力而为。

var myvalue = "hello bye";
var searchReg = new RegExp('(' + myvalue.replace(/ /g, ')[-. ]*?(') + ')', 'g');
console.log(searchReg.source);
//-> (hello)[-. ]*?(bye)
var myText = "hellobye is here and hello-bye here and hello.bye";

console.log(myText.replace(searchReg, '$1^^^^^$2'));
// -> hello^^^^^bye is here and hello^^^^^bye here and hello^^^^^bye

如果您不需要反向引用,则阅读起来会更容易一些:

var searchReg = new RegExp(myvalue.replace(/ /g, '[-. ]*?'), 'g');

暂无
暂无

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

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