I need to use regex in C# to split up something like “21A244” where
- The first two numbers can be 1-99
- The letter can only be 1 letter, A-Z
- The last three numbers can be 111-999
So I made this match
“([0-9]+)([A-Z])([0-9]+)”
but for some reason when used in C#, the match functions just return the input string. So I tried it in Lua, just to make sure the pattern was correct, and it works just fine there.
Here’s the relevant code:
var m = Regex.Matches( mdl.roomCode, "(\\d+)([A-Z])(\\d+)" );
System.Diagnostics.Debug.Print( "Count: " + m.Count );
And here’s the working Lua code in case you were wondering
local str = "21A244"
print(string.match( str, "(%d+)([A-Z])(%d+)" ))
Thank you for any help
EDIT: Found the solution
var match = Regex.Match(mdl.roomCode, "(\\d+)([A-Z])(\\d+)");
var group = match.Groups;
System.Diagnostics.Debug.Print( "Count: " + group.Count );
System.Diagnostics.Debug.Print("houseID: " + group[1].Value);
System.Diagnostics.Debug.Print("section: " + group[2].Value);
System.Diagnostics.Debug.Print("roomID: " + group[3].Value);
Firstly you should make your regex a little more specific and limit how many numbers are allowed at the beginning/end. How about:
([1-9]{1,2})([A-Z])([1-9]{1,3})Next, the results of the captures (i.e. the 3 parts in parens) will be in the
Groupsproperty of your regex matcher object. I.e.