网站搜索

TypeScript 导入 { RegExp }


我想在 TypeScript 中使用正则表达式,但在 Visual Studio Code 中它被标记为错误。

            import { RegExp } from "RegularExpressions/Regex"; // module not found.
            export class BotAnswerRegex {
                createRegex(){
                    var regex = new RegExp('hi');
                    // regex.isMatch is marked as an error
                    var result = regex.isMatch('hi, i am peter');
                }
            }

我正在按照文档操作。http://electricessence.github.io/TypeScript.NET/documentation/classes/_source_system_text_regularexpressions_.regex.html

更新:修复变量声明

答案#1

要使用这个库,你的代码应该像这样:

import RegExp from "typescript-dotnet-commonjs/System/Text/RegularExpressions";
// ...
let regex = new RegExp('hi');
let result = regex.isMatch('hi, i am peter');
// ...
console.log(result);
// ...

更新

注意,你的代码不正确,你正在声明一个局部变量:

var regex = new RegExp('hi');

而你正在尝试使用 this 访问这个变量:

... this.regex.isMatch('hi, i am peter');