[英]Regex with numbers and special characters but no letters
I'm making a regex that accepts an input with any decimal(0-9), +, * or # but shouldn't accept any letters(az). 我正在制作一个接受带有任何小数(0-9),+,*或#的输入的正则表达式,但不应接受任何字母(az)。
so numbers like 所以数字就像
should be accepted. 应该被接受。
The regex is invalid when there is any letter in the string. 当字符串中有任何字母时,正则表达式无效。
This is the regex I have so far: 这是我到目前为止的正则表达式:
private const string PhoneNumberRegex = "((\\d)|(\\*)|(\\#)|(\\+))?";
private bool IsValid(inputString)
{
// Accept * # + and number
Match match = Regex.Match(inputString, PhoneNumberRegex, RegexOptions.IgnoreCase);
return match.Success;
}
But this regex also returns true on #192#abbef 但是这个正则表达式在#192#abbef上也会返回true
How can I fix this? 我怎样才能解决这个问题?
You can use this: 你可以用这个:
private const string PhoneNumberRegex = @"^[0-9*#+]+$";
Where ^
and $
are anchors for start and end of the string. 其中
^
和$
是字符串开头和结尾的锚点。
Note: RegexOptions.IgnoreCase
is not needed. 注意:
RegexOptions.IgnoreCase
。
You need to anchor your string with ^
(begin of line) and $
(end of line). 你需要用
^
(行首)和$
(行尾)锚定你的字符串。 Otherwise your string matches if any part of it matches. 否则,如果匹配的任何部分匹配,则字符串匹配。
Also, you want at least one of those characters (you don't want to match an empty string, so you should use +
(one or more). 此外,您至少需要其中一个字符(您不希望匹配空字符串,因此您应该使用
+
(一个或多个)。
Lastly, you can make a character class out of all your characters: [\\d*#+]
. 最后,你可以用你的所有角色制作一个角色类:
[\\d*#+]
。
Putting it all together gives you: 把它们放在一起就可以了:
private const string PhoneNumberRegex = "^[\\d*#+]+$";
This means that from the beginning of the string till the end, you want one or more of those characters you listed. 这意味着从字符串的开头到结尾,您需要列出的一个或多个字符。
我相信这将满足您的需求
private const string PhoneNumberRegex = @"^([0-9]|#|\+|\*)+$"
Use this : 用这个 :
const string MYRegex = @"^[0-9*#+]+$";
for more information plz visit 有关更多信息,请访问plz
http://www.regexlib.com/Search.aspx?k=special%20characters&AspxAutoDetectCookieSupport=1 http://www.regexlib.com/Search.aspx?k=special%20characters&AspxAutoDetectCookieSupport=1
http://www.cisco.com/en/US/docs/ios_xr_sw/iosxr_r3.4/getting_started/installation/guide/gs34aexp.pdf http://www.cisco.com/en/US/docs/ios_xr_sw/iosxr_r3.4/getting_started/installation/guide/gs34aexp.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.