regular expression to match a pattern
I need a regular expression for c# which can match following pattern
abc1abcd
1abcdefg abcdefg1
basically my expression should have at least one number and min size is 8 char including number. If possible explain the regex开发者_开发百科 also.
I'd probably check with two statements. Just check the length eg
string.Length > 7
and then make sure it this regex can find a match...
[0-9]
You can use a look-ahead assertion to verify the length, and then search forward for a digit, thus:
(?=.{8}).*[0-9]
We look-ahead for 8 characters, and if that is successful, then we actually attempt to match "anything, followed by a digit".
But really, don't do this. Just check the length explicitly. It's much clearer.
Your regular expression pattern should just be: \d+
(match 1 or more numbers). For your example, it's probably best to not determine minimum length using regex since all you care about is that it has at least 1 number and is at least than 8 characters
Regex regEx = new Regex(@"\d+");
isValid = regEx.Match(myString).Success && myString.Length >= 8;
The pattern \d
is just the same as [0-9]
and the +
symbol means at least one of
. The @
symbol in front of the string is so that it what try to escape \d
.
As mentioned by El Ronnoco in the comments, just \d
would match your requirement. Knowing about \d+
is useful for more complicated patterns where you want a few numbers in between some strings,etc.
Also: I've just read something that I didn't know. \d
matches any character in the Unicode number, decimal digit category which is a lot more than just [0-9]
. Something to be aware of if you just want any number. Otherwise El Ronnoco's answer of [0-9]
for your pattern is sufficient.
精彩评论