TypeScript中的RegExp

时间:2013-05-20 11:38:25

标签: javascript regex typescript

如何在TypeScript中实现Regexp?

我的例子:

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

4 个答案:

答案 0 :(得分:50)

我想你想在TypeScript中test你的RegExp,所以你必须这样做:

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

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

为什么test + "" 因为TS中的alert()接受一个字符串作为参数,所以最好以这种方式编写它。您可以尝试完整代码here

答案 1 :(得分:21)

你可以这样做:

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

答案 2 :(得分:4)

在打字稿中,声明是这样的:

const regex : RegExp = /.+\*.+/;

使用RegExp构造函数:

const regex = new RegExp('.+\\*.+');

答案 3 :(得分:0)

Regex文字符号通常用于创建RegExp

的新实例。
     regex needs no additional escaping
      v
/    regex   /   gm
^            ^   ^
start      end   optional modifiers

有关测试和正则表达式的解释,请参见:https://regex101.com/r/Zb8s01/3

const regex = /myRegexp/

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

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

regex: 12\d45
matches: 12345

const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/