Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在正则表达式中使用变量?_Javascript_Regex - Fatal编程技术网

Javascript 如何在正则表达式中使用变量?

Javascript 如何在正则表达式中使用变量?,javascript,regex,Javascript,Regex,我想在JavaScript中创建一个String.replaceAll()方法,我认为使用正则表达式是最简洁的方法。但是,我不知道如何将变量传递给正则表达式。我已经可以这样做了,它将用“A”替换“B”的所有实例 但我想这样做: String.prototype.replaceAll = function(replaceThis, withThis) { this.replace(/replaceThis/g, withThis); }; str1 = "pattern" var re

我想在JavaScript中创建一个
String.replaceAll()
方法,我认为使用正则表达式是最简洁的方法。但是,我不知道如何将变量传递给正则表达式。我已经可以这样做了,它将用
“A”
替换
“B”
的所有实例

但我想这样做:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"

但是很明显,这只会替换文本
“replaceThis”
…那么如何将此变量传递到我的正则表达式字符串?

您可以构造一个新对象,而不是使用
/regex\d/g
语法:

您可以通过这种方式动态创建regex对象。然后你会做:

"mystring1".replace(re, "newstring");
这:

相当于:

var txt=/pattern/attributes;

请参阅。

正如Eric Wendelin提到的,您可以执行以下操作:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"
这将产生“正则表达式匹配”。。但是,如果str1是
,它将失败。您希望结果是
“模式匹配正则表达式”
,将句点替换为
“正则表达式”
,但结果是

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
这是因为,尽管
是一个字符串,但在RegExp构造函数中它仍然被解释为正则表达式,表示任何非换行字符,表示字符串中的每个字符。为此,以下功能可能有用:

 RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
 };
然后你可以做:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

产生
“模式匹配正则表达式”

虽然您可以创建动态创建的正则表达式(根据对这个问题的其他回答),但我将回应a中的评论:的函数形式非常有用,在许多情况下减少了对动态创建的正则表达式对象的需要。(这是一种痛苦,因为您必须将RegExp构造函数的输入表示为字符串,而不是使用斜杠/[a-Z]+/RegExp文本格式)

“ABABAB”。替换(/B/g,“A”)

和往常一样:除非必须,否则不要使用正则表达式。对于简单的字符串替换,习惯用法是:

'ABABAB'.split('B').join('A')
那么,您就不必担心Gracenotes回答中提到的引用问题

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

用这个

进行测试对于任何想用匹配方法来使用变量的人来说,这对我来说是有效的

var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight

下面是另一个replaceAll实现:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

为了满足在正则表达式中插入变量/别名/函数的需要,我提出了以下建议:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
其中'oldre'是我要插入变量的原始regexp, “xx”是该变量/别名/函数的占位符,
“yy”是实际的变量名、别名或函数。

如果$1不能使用,您可以使用它

var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");
var模式=新的RegExp(“安曼”、“我”);
“abc安曼efg”。替换(模式“+”abc安曼efg。匹配(模式)[0]+”);

您始终可以重复使用
索引of

String.prototype.replaceAll = function(substring, replacement) {
    var result = '';
    var lastIndex = 0;

    while(true) {
        var index = this.indexOf(substring, lastIndex);
        if(index === -1) break;
        result += this.substring(lastIndex, index) + replacement;
        lastIndex = index + substring.length;
    }

    return result + this.substring(lastIndex);
};
当替换包含匹配项时,这不会进入无限循环

String.prototype.replaceAll = function(a, b) {
    return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}
像这样测试它:

var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'

console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
var whather='a[b]句子中的一些[b]随机[/b]文本。[/b]
console.log(whatever.replaceAll(“[”,“))

您希望动态构建正则表达式,为此,正确的解决方案是使用
新的RegExp(string)
构造函数。为了让构造函数按字面意义处理特殊字符,必须对其进行转义。在名为
$.ui.autocomplete.escapeRegex的函数中有一个内置函数:

[…]您可以使用内置的
$.ui.autocomplete.escapeRegex
函数。只需一个字符串 参数,并对所有正则表达式字符进行转义,使结果可以安全地保存 传递到
newregexp()

如果您使用的是jQuery UI,则可以使用该函数,或复制其定义:

然后像这样使用它:

String.prototype.replaceAll = function(replaceThis, withThis) {
    this.replace(/replaceThis/g, withThis);
};
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
//            escapeRegex("[z-a]")       -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result                            -> "[a-z][a-z][a-z]"

还有Steven Penny答案的coffeescript版本,因为这是#2谷歌搜索结果…即使咖啡只是删除了很多字符的javascript…)

在我的特殊情况下

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"
您的解决方案如下:

我实现的方法是从一个文本字段中获取值,该字段是您要替换的字段,另一个是“替换为”文本字段,从变量中的文本字段中获取值,并将变量设置为RegExp函数以进一步替换。在我的例子中,我使用的是Jquery,您也可以仅通过JavaScript来完成

JavaScript代码:

  var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
  var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.

  var sRegExInput = new RegExp(replace, "g");    
  $("body").children().each(function() {
    $(this).html($(this).html().replace(sRegExInput,replace_with));
  });
这段代码是关于Onclick事件的一个按钮,你可以把它放在一个函数中调用


现在,您可以在replace函数中传递变量。

如果您想获取所有出现的(
g
),请不区分大小写(
i
),并使用边界,使其不是另一个单词中的一个单词(
\\b
):


例如:

let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.

这些答案我都不清楚。我最终在一家公司找到了一个很好的解释

答案很简单:

var search_term = new RegExp(search_term, "g");    
text = text.replace(search_term, replace_term);
例如:

$(“按钮”)。单击(函数(){
查找和替换(“Lorem”、“巧克力”);
查找和替换(“ipsum”、“冰淇淋”);
});
函数Find_和replace(搜索搜索项、替换项){
text=$(“textbox”).html();
var search_term=新的RegExp(search_term,“g”);
text=text.replace(搜索词,替换词);
$(“文本框”).html(文本);
}

益智益智益智益智益智益智益智益智益智益智益智益智益智益智益智益智益智

单击我
获取不带正则表达式的多个替换我使用了以下内容:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs
let str=“我是一个爱猫的人,我喜欢猫”;
让我们找到“猫”;
让我们替换“狗”;
//计算要查找的字符串的出现次数
//在待检查的str内。
让findCount=str.split(find).length-1;
设loopCount=0;
while(loopCount

此自调用函数将使用索引在replacerItems上迭代,并在每次传递时全局更改字符串上的replacerItems[index]

  const replacerItems = ["a", "b", "c"];    

    function replacer(str, index){
          const item = replacerItems[index];
          const regex = new RegExp(`[${item}]`, "g");
          const newStr = str.replace(regex, "z");
          if (index < replacerItems.length - 1) {
            return replacer(newStr, index + 1);
          }
          return newStr;
    }

// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
const replacerItems = ["a", "b", "c"]; function replacer(str, index){ const item = replacerItems[index]; const regex = new RegExp(`[${item}]`, "g"); const newStr = str.replace(regex, "z"); if (index < replacerItems.length - 1) { return replacer(newStr, index + 1); } return newStr; } // console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
var yourFunction = new RegExp(
        '^-?\\d+(?:\\.\\d{0,' + yourVar + '})?'
      )