TypeScript中的RegExp

zra*_*zdn 54 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
Run Code Online (Sandbox Code Playgroud)

Nic*_*ngo 56

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

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

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

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

  • 因为您正在从字符串创建RegExp对象,所以您也需要转义反斜杠:`new RegExp('^ [1-9] \\ d {0,2} $')`或使用正则表达式文字表示法:/^ [1-9]\d {0,2} $ /` (5认同)

seb*_*day 31

你可以这样做:

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

  • regex.test 不是函数。 (5认同)

小智 10

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

const regex : RegExp = /.+\*.+/;
Run Code Online (Sandbox Code Playgroud)

使用 RegExp 构造函数:

const regex = new RegExp('.+\\*.+');
Run Code Online (Sandbox Code Playgroud)


Ari*_*Ari 9

const regex = /myRegexp/

console.log('Hello myRegexp!'.replace(regex, 'World')) // = Hello World!
Run Code Online (Sandbox Code Playgroud)

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

     regex needs no additional escaping
      v
/    regex   /   gm
^            ^   ^
start      end   optional modifiers
Run Code Online (Sandbox Code Playgroud)

正如其他人建议的那样,您还可以使用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/
Run Code Online (Sandbox Code Playgroud)