Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas
I've 开发者_开发技巧been bashing my head against the wall trying to do what should be a simple regex - I need to match, eg 12po
where the 12
part could be one or two digits, then an optional non-alphanumeric like a :.-,_
etc, then the string po
.
The eventual use is going to be in C#
but I'd like it to work in regular grep
on the command line as well. I haven't got access to C#
, which doesn't help.
^[0-9]{1,2}[:.,-]?po$
Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.
^\d{1,2}[\W_]?po$
\d
defines a number and {1,2}
means 1 or two of the expression before, \W
defines a non word character.
^[0-9][0-9]?[^A-Za-z0-9]?po$
You can test it here: http://www.regextester.com/
To use this in C#,
Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
//Do Something
}
Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)
精彩评论