0

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);
5
  • 1
    Just to cover the bases, you do know the capture groups are in m.Groups, yes? Commented Sep 28, 2012 at 9:05
  • I'm too new in regular expressions in C# and I don't have lots of experience to help you, but maybe you could use regexhero.net/tester and test your regular expression there, you make have in your mind that regular expressions may not be written the same way in different languages. Commented Sep 28, 2012 at 9:05
  • I got [0-9]+[A-Z]+[0-9]+ maybe this helps :) Commented Sep 28, 2012 at 9:07
  • @user1705730 In RegExHero Tester, says your regular expression fits good for the string sample you give, can you give a sample that doesn't work for your regular expression? Thank you Commented Sep 28, 2012 at 9:10
  • Thank you all for the quick responses! Commented Sep 28, 2012 at 9:15

2 Answers 2

1

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 Groups property of your regex matcher object. I.e.

m.Groups[1] // First number
m.Groups[2] // Letter
m.Groups[3] // Second number
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! (need more characters blabla)
0

Regex.Matches(mdl.roomCode, "(\d+)([A-Z])(\d+)") returns an collection of matches. If there is no match, then it will return an empty MatchCollection.

Since the regular expression matches the string, it returns a colletion with one item, the input string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.