我正在用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?


当前回答

你可以使用复选框来请求标志,然后做这样的事情:

var userInput = formInput;
var flags = '';
if(formGlobalCheckboxChecked) flags += 'g';
if(formCaseICheckboxChecked) flags += 'i';
var reg = new RegExp(userInput, flags);

其他回答

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

我发现@Richie Bendall的解决方案非常干净。我添加了一些小的修改,因为当传递非正则字符串时,它会崩溃并抛出错误(也许这就是你想要的)。

const stringToRegex = (str) => {
const re = /\/(.+)\/([gim]?)/
const match = str.match(re);
if (match) {
    return new RegExp(match[1], match[2])
}

}

使用(gim) ?在模式中,如果匹配的[2]值无效,将忽略它。你可以省略[gim]?模式,如果您希望在正则表达式选项无效时抛出错误。

这是一个一行程序:str.replace (/[|\\{}()[\]^$+*?.) / g, ' \ \ $ &’)

我从escape-string-regexp NPM模块中得到的。

尝试一下:

escapeStringRegExp.matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
function escapeStringRegExp(str) {
    return str.replace(escapeStringRegExp.matchOperatorsRe, '\\$&');
}

console.log(new RegExp(escapeStringRegExp('example.com')));
// => /example\.com/

使用带标记的模板文字支持:

function str2reg(flags = 'u') {
    return (...args) => new RegExp(escapeStringRegExp(evalTemplate(...args))
        , flags)
}

function evalTemplate(strings, ...values) {
    let i = 0
    return strings.reduce((str, string) => `${str}${string}${
        i < values.length ? values[i++] : ''}`, '')
}

console.log(str2reg()`example.com`)
// => /example\.com/u

使用RegExp对象构造函数从字符串创建正则表达式:

var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
var flags = inputstring.replace(/.*\/([gimy]*)$/, '$1');
var pattern = inputstring.replace(new RegExp('^/(.*?)/'+flags+'$'), '$1');
var regex = new RegExp(pattern, flags);

or

var match = inputstring.match(new RegExp('^/(.*?)/([gimy]*)$'));
// sanity check here
var regex = new RegExp(match[1], match[2]);