Need help with a regex
Hi I'm trying to right a r开发者_StackOverflow中文版egular expression that will take a string and ensure it starts with an 'R' and is followed by 4 numeric digits then anything
eg. RXXXX.................
Can anybody help me with this? This is for ASP.NET
You want it to be at the beginning of the line, not anywhere. Also, for efficiency, you dont want the .+
or .*
at the end because that will match unnecessary characters. So the following regex is what you really want:
^R\d{4}
This should do it...
^R\d{4}.*$
\d{4}
matches 4 digits.*
is simply a way to match any character 0 or more times- the beginning
^
and end$
anchors ensure that nothing precedes or follows
As Vincent suggested, for your specific task it could even be simplified to this...
^R\d{4}
Because as you stated, it doesn't really matter what follows.
/^R\d{4}.*/
and set the case insensitive option unless you only want capital R's
^R\d{4}.*
- The caret
^
matches the position before the first character in the string. \d
matches any numeric character (it's the same as [0-9]){4}
indicates that there must be exactly 4 numbers, and.*
matches 0 or more other characters
To use:
string input = "R0012 etc..";
Match match = Regex.Match(input, @"^R\d{4}.*", RexOptions.IgnoreCase);
if (match.Success)
{
// Success!
}
Note the use of RexOptions.IgnoreCase
to ignore the case of the letter R (so it'll match strings which start with r. Leave this out if you don't want to undertake a case insensitive match.
精彩评论