新的RegExp('^ \ + \d {2} \.\\\ {10} $')不起作用 [英] new RegExp('^\+\d{2}\.\d{10}$') doesn't work

查看:582
本文介绍了新的RegExp('^ \ + \d {2} \.\\\ {10} $')不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试字符串的格式。此字符串应以 + 符号开头,然后是2位数字,然后是符号,然后是10位数。

I want to test a string's format. This string should start with a + sign, then 2 digits, then a . sign, then 10 digits.

/^\+\d{2}\.\d{10}$/.test('+34.2398320186');

这样,它可以工作(你可以测试它)。但是当我使用 RegExp 时,它表示语法有无效的量词错误。怎么了?

This way, it works (you can test it). But when I use RegExp, it says that the syntax has invalid quantifier error. What's wrong?

推荐答案

你必须逃避 \ 第二个 \\

new RegExp('^\\+\\d{2}\\.\\d{10}$'); // should work

我将从 http://www.regular-expressions.info/javascript.html


我建议您不要将RegExp构造函数与文字
字符串一起使用,因为在文字字符串中,必须对反斜杠进行转义。

I recommend that you do not use the RegExp constructor with a literal string, because in literal strings, backslashes must be escaped.

这篇关于新的RegExp('^ \ + \d {2} \.\\\ {10} $')不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆