Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

C#RegexGrep

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

^[0-9]{1,2}[:.,-]?po$

Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.

Solution 2 - C#

^\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.

Solution 3 - C#

^[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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenView Question on Stackoverflow
Solution 1 - C#eykanalView Answer on Stackoverflow
Solution 2 - C#stemaView Answer on Stackoverflow
Solution 3 - C#TimCodes.NETView Answer on Stackoverflow