• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 216
  • Last Modified:

Regular Expression and backreferencing groups

I need help with a regular expression.

I have input strings like:
(DCS 1234)
(DCS 1234, 5678)
(DCS 1234, 5678, 9876)

I need to be able to match these strings and back-reference the numbers.

I have started with something like:

Regex reDCSList = new Regex(@"\(DCS ((,*\d{4})+).*");

but is only groups the first 1234, I never get the following numbers.

Any help would be appreciated.

2 Solutions
the way you have done the grouping means that it will look for one set of numbers as group 1, then include the rest of the string in the match but not as part of any group.

this regex will match all of the groups of numbers into group 1,  then you will need to split it up by commas
\(DCS ([\d{4},?\s?]+)\)

to get an array of the numbers as strings:
string s = match.Groups[1];
string[] numbers = s.Replace(" ", "").Split(",") //this trims out the spaces and then splits it up at the commas
@"\(DCS ((,*\s*\d{4})+).*"
Regex regex = new Regex(@"\(DCS(?: (?<number>\d{4}),)* (?<number>\d{4})\)");
Group group = regex.Match("(DCS 1234, 5678, 9876)").Groups["number"];
foreach(Capture capture in group.Captures)
aogusafaAuthor Commented:
Thanks Experts!

I split the points up because Solar Flare showed me how to access the data once it had been matched, but I liked the elegance of ozo's RE.

Works great.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now