Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 213
  • 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.

Jer
0
aogusafa
Asked:
aogusafa
2 Solutions
 
Solar_FlareCommented:
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
0
 
ozoCommented:
@"\(DCS ((,*\s*\d{4})+).*"
0
 
icrCommented:
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)
{
    Console.WriteLine(capture.Value);
}
0
 
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.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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