我有一个框,用户在其中输入正则表达式,在 Javascript 中,我采用该值并用它测试另一个字符串,如下所示:(这是我真正问题的抽象)
var regex = $('input').val();
regex.test('some string');
我知道确保将 regex
转换为安全的 Object
类型的唯一方法是使用 eval()
。
这是最好的转换方式吗?
最佳答案
使用 RegExp 构造函数创建模式。
// The next line would escape special characters. Since you want to support
// manually created RegExps, the next line is commented:
// regex = regexp.replace(/([[^$.|?*+(){}])/g, '\\$1')
regex = new RegExp(regex);
// ^ Optionally, add the flags as a second argument, eg:
//regex=new RegExp(regex, 'i'); //Case-insensitive
更新
您似乎误解了 RegExp
构造函数的用法。 “斜杠符号”是创建正则表达式的“原始”方式。为了进行比较,请考虑(new
是可选的):
"123" === new String(123)
false === new Boolean(1)
// Because a RegExp is an object, the strict compare `===` method evaluates to
// false if the pattern is not the same object.
// Example: /\d/ == /\d/ evaluates to false
// To compare a regex pattern, use the `pattern` property
/[a-z]/i.pattern === (new RegExp("[a-z]", "i")).pattern
RegExp
构造函数采用两个参数,第二个参数是可选的:
- 字符串 模式(没有尾部和结尾斜杠)
字符串(可选) 标志组合:
i
(忽略大小写)g
(全局匹配)m
(多行(很少使用))。
示例(new
是可选的):
Using constructor using slash-notation # Notice:
RegExp('[0-9]'); /[0-9]/ # no slashes at RegExp
RegExp('/path/to/file\.html$') /path\/to\/file\.html$/ # the escaped \
RegExp('i\'m', 'i') /i'm/i # \' vs ', 'i' vs /i
使用斜杠符号实现“RegExp”表单字段
var regex = $('input').val(); //Example: '/^[0-9]+$/i'
// Using a RegEx to implement a Reg Exp, ironically..
regex = regex.match(/^\/([\S\s]+)\/([gim]{0,3})$/);
regex = regex || [, regex, ""]; // If the previous match is null,
// treat the string as a slash-less RegEx
regex = new RegExp(regex[1], regex[2]);
regex.test('some string');
关于javascript 将正则表达式字符串转换为类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429620/