简体   繁体   English

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

[英]regex match variations of multiple words

I have stored my value in a variable: 我已经将我的值存储在一个变量中:

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

how can I check if the variations of myvalue appears in the text? 如何检查myvalue的变体是否出现在文本中?
i am using this pattern: 我正在使用这种模式:

hello[-. ]*?bye

but i can't break my variable value like this. 但是我不能破坏我这样的变量值。 One more thing, what if my value contains more than two elements? 还有一件事,如果我的值包含两个以上的元素怎么办? like hello bye hi hello bye hi

You may replace all whitespace chunks (match them with a mere /\\s+/g ) with [-.\\\\s]*? 您可以用[-.\\\\s]*?替换所有空白块(仅用/\\s+/g匹配它们) [-.\\\\s]*? to create a regex to match the variations of myvalue : 创建一个正则表达式以匹配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'))); 

I think something like this is what you are after. 我认为您追求的是这样的事情。 If you want an explanation, leave a comment and I will do my best. 如果您需要解释,请发表评论,我会尽力而为。

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

If you don't need back references, it's a little easier to read: 如果您不需要反向引用,则阅读起来会更容易一些:

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

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

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