0

PHP の私のコードは、ユーザー入力に基づいて JSON を生成します。

この JSON 内には、区切り記号付きの正規表現文字列 "/regex/gi" があります。

これをユーザーに送信し、javascript でその正規表現に基づいて文字列をテストしたいと思います。しかし、文字列内に区切り文字があるため、機能しません。

時々、正規表現文字列を「regex」、「/regex/」、または「/regex/gi」として受け取ることができます。これらの区切り文字を削除する方法、または文字列を正規表現に変換する方法はありますか。

「new RegExp」を使用しようとしましたが、文字列をエスケープしてしまい、機能しません。

ここにいくつかのコード:

var json = {regex: "/hello/"}; //This code is generated by PHP
"hello".match(json.regex); //Test in javascript, not working, since the "/" are inside the regex and not used as delimiter 

どうすればこれを行うことができるか考えている人はいますか?

感謝

4

2 に答える 2

2

あなたはあなたの正規表現を正規表現することができます(すごい迫力)

var reMeta = /(^|[^\\])\/(\w+$){0,1}/;
var json = {regex: "/hello\/slash\//gi"};

json.regex = new RegExp( json.regex.replace(reMeta,'$1') );
// after replace it looks like: "hello\/slash\/"
于 2013-06-25T13:04:05.843 に答える
1
var json = {regex: "/hello/"};

"hello".match(eval(json.regex));//Simle way (bad practice, but will work)

より推進方法:

var json = {regex: "hello"};
var reg = new RegExp(json.regex)
var matched = reg.exec("hello") != null;
于 2013-06-25T12:47:46.143 に答える