正则表达式不能一次使用或不使用 [英] Regex expression not working with once or none

查看:97
本文介绍了正则表达式不能一次使用或不使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的正则表达式:

Below is my regex:

[^4\d{3}-?\d{4}-?\d{4}-?\d{4}$]

但是它会在-处引发错误.我正在使用?,它应该允许-出现零次或一次.为什么会出现错误?

But it throws an error at -. I am using ?, which should allows - to appear zero or one time. Why it is giving errors?

推荐答案

正则表达式的问题在于,模式用[]括起来,被视为字符类标记(请参见

The problem with the regex is that the pattern is enclosed with [ and ] that are treated as character class markers (see Character Classes or Character Sets):

使用字符类"(也称为字符集"),您可以告诉正则表达式引擎仅匹配几个字符中的一个.只需将要匹配的字符放在方括号之间.如果要匹配ae,请使用[ae].

在字符类中,-在文字字符之间创建范围.在您的情况下,这些范围是无效的(从具有较高值的​​字符到具有较低值的字符),因为{4}和其他子模式被视为单独的字符,而不是特殊的构造:

In character classes, - creates ranges between literal characters. In your case, these ranges are not valid (go from a character with higher values to those with lower values) since the {4} and other subpatterns were treated as separate characters, not special constructs:

因此,您要做的就是移除两侧的[]:

So, all you need to do is remove the [ and ] on both sides:

^4\d{3}-?\d{4}-?\d{4}-?\d{4}$

请参见 regex演示.

这篇关于正则表达式不能一次使用或不使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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