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

Use dynamic (variable) string as regex pattern in JavaScript

本文关键字:字符串 模式 正则表达式 变量 JavaScript 动态      更新时间:2023-09-26

我想用正则表达式向值添加一个(变量)标记,该模式在PHP中运行良好,但在JavaScript中实现它时遇到了问题。

模式为(value为变量):

/(?!(?:[^<]+>|[^>]+<'/a>))'b(value)'b/is

我转义了反斜杠:

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

但这似乎是不对的,我记录了这个模式和它应该是什么。有什么想法吗?

要从字符串创建正则表达式,必须使用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.

JSFiddle演示在这里


在一般情况下,在用作regex之前对字符串进行转义:

不过,并不是每个字符串都是有效的正则表达式:有一些特殊字符,如([。要解决这个问题,只需先转义字符串,然后再将其转换为正则表达式。下面的示例中有一个实用函数:

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.

JSFiddle演示在这里



注意:问题中的正则表达式使用s修饰符,该修饰符在问题出现时不存在,但确实存在--JavaScript中的sdotall)标志/修饰符--今天。

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

var regex = "(?!(?:[^<]+>|[^>]+<'/a>))'b(" + value + ")'b";
new RegExp(regex, "is")

我发现我必须对''b进行双斜杠才能使其工作。例如,要使用变量从字符串中删除"1x"单词,我需要使用:

    str = "1x";
    var regex = new RegExp("''b"+str+"''b","g"); // same as inv.replace(/'b1x'b/g, "")
    inv=inv.replace(regex, "");

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

var regex = /(?!(?:[^<]+>|[^>]+<'/a>))'b(value)'b/is; // this is valid syntax

如果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");

请记住,如果value包含像([?这样的正则表达式字符,则需要对它们进行转义。

我发现这个线程很有用,所以我想把答案添加到我自己的问题中。

我想用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 );

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

之前的配置文件:

data_file_directories:  
   - /var/lib/cassandra/data

之后的配置文件

data_file_directories:  
- /mnt/cassandra/data

更简单的方法:使用模板文字。

var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false

使用字符串变量内容作为更复杂的组合正则表达式(es6|ts)的一部分

此示例将使用my-domain.commy-other-domain替换所有url(两者都是变量)。

您可以通过在原始字符串模板中组合字符串值和其他正则表达式来执行动态正则表达式。使用String.raw将防止javascript转义字符串值中的任何字符。

// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '''.
const regexUrl = /'./gm;    
const substr = `'''.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain'.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([''|'"]https:'/'/)(${domain})('S+[''|'"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);

注意:不要忘记使用regex101.com来创建、测试和导出REGEX代码。

var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'

https://jsfiddle.net/9f0mb6Lz/

希望这能帮助