[英]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.