Reputation: 1263
I have to write a function that will get a string and it will have 2 forms:
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)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
Upvotes: 1
Views: 104
Reputation: 336108
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.
Upvotes: 3