簡體   English   中英

在 JavaScript 中使用動態(可變)字符串作為正則表達式模式

[英]Use dynamic (variable) string as regex pattern in JavaScript

我想使用正則表達式向值添加一個(變量)標簽,該模式適用於 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 演示在這里。


在一般情況下,在用作正則表達式之前轉義字符串:

但是,並非每個字符串都是有效的正則表達式:有一些特殊字符,例如([ 。要解決此問題,只需在將字符串轉換為正則表達式之前將其轉義即可。下面的示例中有一個實用函數:

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 中的s ( dotall ) 標志/修飾符 - today

如果您嘗試在表達式中使用變量值,則必須使用 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.com的 url 替換為my-other-domain (兩者都是變量)。

您可以通過在原始字符串模板中組合字符串值和其他正則表達式來執行動態正則表達式。 使用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 代碼。

const yourVariable: string = 'test';
let regexp = new RegExp(yourVariable, flags);

regexp = new RegExp(yourVariable, 'g'); // In this case, global flag is applied

output: /test/g
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/

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM