RLewis
RLewis

Reputation: 87

Double digits and single digits using Regex

I currently have the regex:

(?:(?:CD)|(?:DISC)|(?:DISK)|(?:PART))([0-9]+)

currently this will match CD1, DISK2 etc

I need it too be able to pick up CD02 (with two digits) as well as CD2 but I only seem to be able to do one or the other, and my regex skills are pretty useless.

I'm using this code in C#

thanks for your help

Russell

Upvotes: 1

Views: 1203

Answers (4)

Jeff
Jeff

Reputation: 561

Could it be that you're looking for the entire string "CD2" or "CD02" in a capture group? As in:

string input = "CD02";
var labelMatch = Regex.Match(input, "(?:(?:CD|... // edit for brevity
if(labelMatch.Success)
{
   string labelText = mediaLabel.Groups[1].Value;
}

You may have made a mistake by using the ?: expression because this tells the regex engine to match the group and then discard it from the capture groups. Some other expressions you might want to consider:

(?:CD|DISC|DISK|PART)(\d\d?)    // throws away the label, captures 1 or 2 digits
(?:CD|DISC|DISK|PART)(\d{1,2})  // ~same thing, matches exactly 1 or 2 digits
((CD|DISC|DISK|PART)\d\d?)      // captures the whole thing in group 1

Upvotes: 0

Jeff Moser
Jeff Moser

Reputation: 20053

It works here. Can you post your code that is failing?

Note that your Regex can be simplified:

bool isMatch = Regex.IsMatch("CD02", "(?:(?:CD)|(?:DISC)|(?:DISK)|(?:PART))([0-9]+)");
bool isSimplifiedMatch = Regex.IsMatch("CD02", "(?:(CD|DIS[CK]|PART))([0-9]+)");

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882776

That will match CD02 because you have the "[0-9]+" section in there which means one or more of any digit.

It would only match CD2 and not CD02 if you had something like "[1-9][0-9]*".

Upvotes: 0

Steve Wortham
Steve Wortham

Reputation: 22260

This seems to work for me. Actually, I tested it in Regex Hero (.NET) and The Regex Coach (Perl) and they both work. It'll match CD2 and CD02.

Perhaps there's an issue in your C# code?

Upvotes: 0

Related Questions