正则表达式模式引发了一个词法分析器错误 AngularJS

4

在输入框使用ng-pattern时,我遇到了词法分析器错误。

我的正则表达式是用来测试电话号码的,在输入框中它看起来像这样:

<input 
    type="text"
    class="phone"
    ng-pattern="(\(?([0-9]{3})\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})"
    placeholder="Phone Number" ng-model="contactFormVM.contact.phone"
    required />

然后Angular向我发出警告,并给了我这个错误:
Error: [$parse:lexerr] Lexer Error: Unexpected next character  at columns 1-1 [\] in expression [(\(?([0-9]{3})\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})].

现在我可以看到它对我的 \ 感到生气。但是我不知道如何在不转义它的情况下编写正则表达式。有趣的是,测试实际上有效并且正确验证,但我讨厌无缘无故地抛出错误。
有任何想法为什么会发生这种情况吗?
谢谢
1个回答

5

如果您的字符串中包含任何\字符,您需要对其进行转义,因为ngPattern会将该字符串包装在new RegExp('stringhere')中,这要求您对该字符进行转义(escape)


ng-pattern="(\(?([0-9]{3})\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})" - George Houpis
你有没有可能使用 ng-pattern=/(\(...\))/ 或者 ng-pattern=(\(...\)) - Aprillion
模式现在看起来像这样 ng-pattern="(\\(?([0-9]{3})\\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})",但我仍然遇到完全相同的错误:Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 1-1 [\] in expression [(\\(?([0-9]{3})\\)?)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})]. - Spittal
@Aprillion,你应该能够做到,因为ngPattern上的注释说它寻找一个正则表达式对象,否则就将字符串包装成一个正则表达式对象。 - Matthew Green
1
@Spittal,你可以尝试将你的正则表达式放在作用域对象中,并以这种方式引用它,看看是否会得到不同的结果。否则,你可能需要编写一个示例片段供大家查看,以进一步解决这个问题。 - Matthew Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接