两个正则表达式模式之间有什么区别 [英] What is the difference between the two regex pattern

查看:215
本文介绍了两个正则表达式模式之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在网络应用程序中验证公司名称并具有此正则表达式模式

I was trying to validate a company name in a web application and had this regex pattern

^[a-zA-Z_'\\s,;.-0-9]{1,100}$

以上模式将拒绝该值 10004 Estates Limited

但如果我提前0-9所以模式变为

But if I bring forward 0-9 so the pattern becomes

^[a-zA-Z0-9_'\\s,;.-]{1,100}$

然后才有效。我是正则表达式和模式的新手,但我知道我应该使用更多,所以我想明确这一点。谢谢。

then it works. Am new to regex and patterns, but I know I should be using more of it, so I want to be clear on this. Thanks.

推荐答案

- 是字符类中的特殊字符,因此 .- 0-9 含糊不清,可能含义 0 - 9 ,所以基本上是字符 ./ 09-

- is a special character in character classes and thus .-0-9 is ambiguous and probably gets the meaning . to 0 and - and 9, so essentially the characters ./09-.

要在字符类中包含连字符减号,您必须将其转义或将其放在字符类的开头或结尾处。字符类(这是你在第二个正则表达式中所做的,也许是偶然的)。

To include a hyphen-minus in a character class you'd either have to escape it or place it at the start or end of the character class (which is what you're doing in the second regex, maybe by accident).

编辑添加:以上猜测似乎是正确的,至少对于。 NET的正则表达式引擎:

Edited to add: Above guess seems to be correct, at least for .NET's regex engine:

PS> [char[]](32..127) -match '[a-zA-Z_''\s,;.-0-9]'

'
,
-
.
/
0
9
;
A
...

这篇关于两个正则表达式模式之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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