TypeScript中的RegExp


73

如何在TypeScript中实现Regexp?

我的例子:

var trigger = "2"
var regex = new RegExp('^[1-9]\d{0,2}$', trigger); // where I have exception in Chrome console

Answers:


78

我认为您想test在TypeScript中使用RegExp,所以您必须这样做:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

您应该阅读MDN参考-RegExp,该RegExp对象接受两个参数,pattern并且flags该参数可以为null(可以省略/未定义)。要测试您的正则表达式,您必须使用.test()方法,而不是在RegExp的声明中传递要测试的字符串!

为什么test + "" 因为alert()在TS中接受字符串作为参数,所以最好这样写。您可以在此处尝试完整的代码。


如果var trigger =“ 10”,则regexp =新的RegExp('^ [1-9] \ d {0,2} $'),test = regexp.test(trigger); alert(test +“”); 警报返回false,表示不正确
zrabzdn

这种替换当前的正则表达式模式:'^([0-9]\d{0,2})+$'
尼可罗马基Campolungo

6
因为您是从字符串创建RegExp对象,所以您也需要转义反斜杠:new RegExp('^[1-9]\\d{0,2}$')或使用regex文字表示法:/^[1-9]\d{0,2}$/
Sly_cardinal

39

您可以执行以下操作:

var regex = /^[1-9]\d{0,2}$/g
regex.test('2') // outputs true


2

const regex = /myRegexp/

console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!

正则表达式的文字符号通常用于创建新实例RegExp

     regex needs no additional escaping
      v
/    regex   /   gm
^            ^   ^
start      end   optional modifiers

正如其他人建议的那样,您也可以使用new RegExp('myRegex')构造函数。
但是您在转义时必须格外小心:

regex: 12\d45
matches: 12345

const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.