在JavaScript中使用动态(变量)字符串作为正则表达式模式

Bor*_*rst 74 javascript regex string

我想用一个带有正则表达式的值添加一个(变量)标签,该模式适用于PHP,但我在将它实现到JavaScript时遇到了麻烦.

模式是(value是变量):

/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
Run Code Online (Sandbox Code Playgroud)

我逃脱了反斜杠:

var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "<a href='#" + value +">" + value + "</a>"));
Run Code Online (Sandbox Code Playgroud)

但这似乎不对,我记录了模式,它应该是它应该是什么.有任何想法吗?

acd*_*ior 133

要将正则表达式创建为字符串,您必须使用JavaScript的RegExp对象.

此外,您可能希望匹配/替换多次.在这种情况下,添加g(全局匹配)标志.这是一个例子:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Run Code Online (Sandbox Code Playgroud)

JSFiddle演示在这里.


在一般情况下,在使用正则表达式之前转义字符串:

但是并非每个字符串都是有效的正则表达式:有一些特殊字符,比如([.要解决此问题,只需转义字符串,然后再将其转换为正则表达式.其实用功能如下:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Run Code Online (Sandbox Code Playgroud)

JSFiddle演示在这里.


对于有问题的具体情况,请注意JavaScript中没有s(dotall)标志/修饰符.在可用的地方,它通常会强制dot(s)匹配换行符.这是您的案例的可能解决方案:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
Run Code Online (Sandbox Code Playgroud)

注意我RegExp在最后添加了一个缺失g.

在这里看演示小提琴.您可能还想使用"g"修饰符尝试此解决方案.

  • 这是很棒的,到目前为止,我已经找到了在正则表达式中使用动态变量的最佳示例,谢谢! (2认同)

hap*_*rry 10

如果您尝试在表达式中使用变量值,则必须使用RegExp"构造函数".

var regex="(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
Run Code Online (Sandbox Code Playgroud)


Hal*_*yon 7

您不需要"定义正则表达式,所以只需:

var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
Run Code Online (Sandbox Code Playgroud)

如果value是一个变量并且你想要一个动态的正则表达式,那么你不能使用这个表示法;使用替代符号。

String.replace 也接受字符串作为输入,所以你可以做 "fox".replace("fox", "bear");

选择:

var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Run Code Online (Sandbox Code Playgroud)

请记住,如果value包含正则表达式字符,如([?你需要躲避他们的。

  • 除非寻找字符串“value”,否则第一个选项将不起作用 (2认同)

小智 6

我发现我必须双斜线 \b 才能让它工作。例如,要使用变量从字符串中删除“1x”单词,我需要使用:

    str = "1x";
    var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
    inv=inv.replace(regex, "");
Run Code Online (Sandbox Code Playgroud)


小智 5

我发现这个线程很有用 - 所以我想我会为我自己的问题添加答案。

我想从 javascript 中的节点应用程序编辑数据库配置文件(datastax cassandra),并且对于我需要匹配字符串的文件中的一项设置,然后替换它后面的行。

这是我的解决方案。

dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'

// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
    // need to use double escape '\\' when putting regex in strings !
    var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
    var myRegExp = new RegExp(searchString + re, "g");
    var match = myRegExp.exec(data);
    var replaceThis = match[1];
    var writeString = data.replace(replaceThis, newString);
    fs.writeFile(file, writeString, 'utf-8', function (err) {
    if (err) throw err;
        console.log(file + ' updated');
    });
});
}

searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"

replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
Run Code Online (Sandbox Code Playgroud)

运行后,它会将现有的数据目录设置更改为新的:

之前的配置文件:

data_file_directories:  
   - /var/lib/cassandra/data
Run Code Online (Sandbox Code Playgroud)

配置文件后:

data_file_directories:  
- /mnt/cassandra/data
Run Code Online (Sandbox Code Playgroud)