1

I have to write a function that will get a string and it will have 2 forms:

  1. XX..X,YY..Y where XX..X are max 4 characters and YY..Y are max 26 characters(X and Y are digits or A or B)
  2. XX..X where XX..X are max 8 characters (X is digit or A or B)

e.g. 12A,784B52 or 4453AB

How can i user Regex grouping to match this behavior?

Thanks.

p.s. sorry if this is to localized

1
  • 2
    You should provide some actual examples of what is valid and what is not Commented Dec 8, 2011 at 10:47

1 Answer 1

3

You can use named captures for this:

Regex regexObj = new Regex(
    @"\b                   # Match a word boundary
    (?:                  # Either match
     (?<X>[AB\d]{1,4})   #  1-4 characters --> group X
     ,                   #  comma
     (?<Y>[AB\d]{1,26})  #  1-26 characters --> group Y
    |                    # or
     (?<X>[AB\d]{1,8})   #  1-8 characters --> group X
    )                    # End of alternation
    \b                   # Match a word boundary", 
    RegexOptions.IgnorePatternWhitespace);
X = regexObj.Match(subjectString).Groups["X"].Value;
Y = regexObj.Match(subjectString).Groups["Y"].Value;

I don't know what happens if there is no group Y, perhaps you might need to wrap the last line in an if statement.

Sign up to request clarification or add additional context in comments.

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.