简体   繁体   English

数字的正则表达式,一些特殊字符和NULL

[英]Regex for Numbers, some special characters and NULL

I want to create a regex which would allow 我想创建一个正则表达式,将允许

0-9
.
>
<
%
,
-
NULL

so I wrote a regex like ^[0-9.><%,-NULL]*$ 所以我写了一个正则表达式,例如^[0-9.><%,-NULL]*$

This matches NULL but should not match when user only enters N . 这匹配NULL,但当用户仅输入N时不匹配。 So I did ^[0-9.&gt;&lt;%,-(NULL)]*$ but I do 所以我做了^[0-9.&gt;&lt;%,-(NULL)]*$但我确实

string pattern = "^[0-9.&gt;&lt;%,-(NULL)]*$";
Regex.Match("N", pattern).Success;

this throws Argument exception and says 这会引发参数异常并说

`parsing "^[0-9.><%,-(NULL)]*$" - [x-y] range in reverse order.

So what should be the correct Regex? 那么正确的正则表达式应该是什么?

I think the expression you need looks similar to this: 我认为您需要的表达式与此类似:

"^([-0-9.><%,]|NULL)*$"

This will match zero or more occurrences of any of the characters in the character set (inside the square brackets) and instances of NULL . 这将匹配字符集中出现的零个或多个字符(在方括号内)和NULL实例。


Making NULL part of your character set will also match the N , U and L characters separately. NULL设置为字符集的一部分还将分别匹配NUL字符。 Attempting to group using (NULL) will not have the desired effect, but will additionally make the character set also match the opening and closing parentheses. 尝试使用(NULL)进行分组不会达到预期的效果,但是会使字符集也与左括号和右括号匹配。

The error you mention ( [xy] range in reverse order ) is caused by the fact that in your expression 您提到的错误( [xy] range in reverse order )是由于表达式中

"^[0-9.><%,-(NULL)]*$"

the hyphen is considered to denote this character range: ,-( . Because the parenthesis precedes the comma, the character range is considered to be in reverse order. 连字符被认为表示此字符范围: ,-( 。因为括号在逗号之前,所以字符范围被认为是相反的顺序。

To represent a hyphen ( - ) in a character set, you need to avoid it being interpreted as denoting a character range. 要在字符集中表示连字符( - ),需要避免将其解释为表示字符范围。 This is most easily achieved by placing the dash at the beginning or the end of the character set. 通过将破折号放在字符集的开头或结尾,可以很容易地实现这一点。

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

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