tags:

views:

248

answers:

5

Hi guys,

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

A: 

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?

Steve Wortham
works for me too, tested with PowerShell
Thomas Levesque
A: 

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]*".

paxdiablo
+2  A: 

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]+)");
Jeff Moser
A: 

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
Jeff
A: 

It turns out there was a small problem with the code. but thanks for all the tips, really useful!

RLewis