Converting user input string to regular expression

I am designing a regular expression tester in HTML and JavaScript. The user will enter a regex, a string, and choose the function they want to test with (eg search, match, replace, etc.) via radio button and the program will display the results when that function is run with the specified arguments. Naturally there will be extra text boxes for the extra arguments to replace and such.

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?


使用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);

要么

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

Use the JavaScript RegExp object constructor.

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

You can pass flags as a second string argument to the constructor. See the documentation for details.

链接地址: http://www.djcxy.com/p/13458.html

上一篇: 有什么方法可以将恶意代码放入正则表达式中吗?

下一篇: 将用户输入字符串转换为正则表达式