我正在用HTML和JavaScript设计一个正则表达式测试器。用户将输入一个正则表达式,一个字符串,并通过单选按钮选择他们想要测试的函数(例如搜索,匹配,替换等),当该函数以指定的参数运行时,程序将显示结果。自然会有额外的文本框用于替换额外的参数等等。

My problem is getting the string from the user and turning it into a regular expression. If I say that they don't need to have //'s around the regex they enter, then they can't set flags, like g and i. So they have to have the //'s around the expression, but how can I convert that string to a regex? It can't be a literal since its a string, and I can't pass it to the RegExp constructor since its not a string without the //'s. Is there any other way to make a user input string into a regex? Will I have to parse the string and flags of the regex with the //'s then construct it another way? Should I have them enter a string, and then enter the flags separately?


当前回答

这也适用于字符串无效或不包含标志等情况:

regExpFromString(q) { Let flags = q.replace(/.*\/([gimuy]*)$/, '$1'); If (flags === q) flags = "; Let pattern = (flags ?q.replace(新RegExp ('^/(.*?)/' + 旗帜 + '$'), '$ 1 '):问); try{返回新的RegExp(模式,标志);} catch (e){返回null;} } console.log (regExpFromString (' \ \ bword \ \ b ')); console.log (regExpFromString(‘\ / \ \ bword \ \ b \ / gi '));

其他回答

使用JavaScript的RegExp对象构造函数。

var re = new RegExp("\\w+");
re.test("hello");

可以将标志作为第二个字符串参数传递给构造函数。详细信息请参见文档。

安全了,但也不安全。(一个不能访问任何其他上下文的函数版本会很好。)

const regexp = Function('return ' + string)()

感谢前面的回答,这个块作为一个通用的解决方案应用一个可配置的字符串到RegEx ..过滤文本:

var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';

var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);

log.debug ('strFilterRegEx: ' + strFilterRegEx);

strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');

我用eval来解决这个问题。

例如:

    function regex_exec() {

        // Important! Like @Samuel Faure mentioned, Eval on user input is a crazy security risk, so before use this method, please take care of the security risk. 
        var regex = $("#regex").val();

        // eval()
        var patt = eval(userInput);

        $("#result").val(patt.exec($("#textContent").val()));
    }

在我的例子中,用户输入有时被分隔符包围,有时没有。所以我又加了一个案例。

var regParts = inputstring.match(/^\/(.*?)\/([gim]*)$/);
if (regParts) {
    // the parsed pattern had delimiters and modifiers. handle them. 
    var regexp = new RegExp(regParts[1], regParts[2]);
} else {
    // we got pattern string without delimiters
    var regexp = new RegExp(inputstring);
}