88

如何在 TypeScript 中实现正则表达式?

我的例子:

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

4 回答 4

92

I think you want to test your RegExp in TypeScript, so you have to do like this:

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

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

于 2013-05-20T11:47:00.613 回答
48

你可以这样做:

var regex = /^[1-9]\d{0,2}$/g
regex.test('2') // outputs true
于 2015-01-13T14:29:02.203 回答
12

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

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

使用 RegExp 构造函数:

const regex = new RegExp('.+\\*.+');
于 2019-07-31T17:07:14.950 回答
6

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
                           Extra excape because it is part of a string
                            v
const regex = new RegExp('12\\d45')
const equalRegex = /12\d45/
于 2019-09-24T12:21:55.617 回答