简体   繁体   English

如何在正则表达式中允许使用“-”?

[英]How do you allow '-' in regular expression?

I am trying to allow '-' in the regular expression for telephone numbers, but the - is usually used for ranges (eg AZ). 我试图在电话号码的正则表达式中允许使用“-”,但是“-”通常用于范围(例如AZ)。 So how do I allow just the character? 那么我如何只允许角色呢? I tried escapting using /-, but that's not working. 我尝试使用/-转义,但这不起作用。

$reg_num = "/[^0-9+ ()]/"; 

You need to escape it with a backslash \\ . 您需要使用反斜杠\\对其进行转义。 So it should be written as \\- . 因此应将其写为\\-

Write it in the end instead of '-' being between two characters. 最后写上它,而不是在两个字符之间写“-”。 Very simplified example: [0-9-] would match 099-2233-3333 where 0-9 is a range, and the - in the end is a seperate dash sign to match. 非常简化的示例: [0-9-] 099-2233-3333 [0-9-]将匹配099-2233-3333 ,其中0-9是范围,最后的-是要匹配的单独破折号。

Put it first in the range, like [^-0-9+ ()] . 将其放在范围内的第一位,例如[^-0-9+ ()] The hyphen needs to separate two characters to define a range; 连字符需要分隔两个字符以定义范围。 if it isn't (in this case because the ^ is also interpreted as a modifier, not a character in the set), then it's just a character in the set like any other. 如果不是(在这种情况下,因为^也被解释为修饰符,而不是集合中的字符),那么它就像集合中的其他字符一样只是集合中的字符。

escaping using \\- 使用\\-转义

\

is escape character! 是逃脱角色!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM