简体   繁体   English

我的Regex表达式有什么问题

[英]What's wrong with my Regex expression

I have a written a Regex to check whether the string consists of 9 digits or not as follows but this always returning me false even if I have my string as 123456789 . 我写了一个Regex来检查字符串是否由9 digits组成,如下所示,但这总是返回false即使我的字符串为123456789

if (Regex.IsMatch(strSSN, " ^\\d{9}$"))

Can any one tell what's wrong and also if any better one provide me .. What i am achieving is the string should have only numeric data and the length should be =9 任何人都可以告诉我什么地方出了问题,也可以告诉我更好的方法是什么。我要实现的是,字符串应仅包含numeric data ,长度应为=9

Spaces are significant in regular expressions (and of course, you can't match a space character before the start of the string). 空格在正则表达式中很重要(当然,在字符串开头之前不能匹配空格字符)。 Remove it and everything should be fine: 删除它,一切都很好:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

Also, you generally want to use verbatim strings for regexes in C#, so you don't have to double your backslashes, but this is just a convenience, not the reason for your problem: 另外,您通常希望对C#中的正则表达式使用逐字字符串,因此不必将反斜杠加倍,但这只是一种方便,而不是引起问题的原因:

if (Regex.IsMatch(strSSN, @"^\d{9}$"))

this should work 这应该工作

^\d{9}$

hope that helps 希望能有所帮助

您在"^之间有一个空格,应该为:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

could it be the space at the beginning of your pattern? 可能是模式开始处的空白吗? That seems wierd, a space then a number anchored to the start of the line. 这似乎很奇怪,在行的开头固定了一个空格,然后是一个数字。

This should give you what you want: 这应该给您您想要的:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

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

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