tags:

views:

319

answers:

2

I am converting Java code to C# and need to replace the use of Java's regex. A typical use is

import java.util.regex.Matcher;
import java.util.regex.Pattern;
//...

String myString = "B12";
Pattern pattern = Pattern.compile("[A-Za-z](\\d+)");
Matcher matcher = Pattern.matcher(myString);
String serial = (matcher.matches()) ? matcher.group(1) : null;

which should extract a capture group from a matched target string. I'd be grateful for simple examples.


EDIT: I have now added the C# equivalent of the code as an answer.

EDIT: Here is a tutorial on the use of the actual expressions.

EDIT: Here is a useful comparison of C# and Java (and Perl.)

+12  A: 

System.Text.RegularExpressions.Regex class is the .NET Framework equivalent. The MSDN page I linked to contains a simple example.

Mehrdad Afshari
A: 

I created the C# equivalent of the Java code in the question as:

string myString = "B12";
Regex rx = new Regex(@"[A-Za-z](\\d+)");
MatchCollection matches = rx.Matches(myString);
if (matches.Count > 0)
{
    Match match = matches[0]; // only one match in this case
    GroupCollection groupCollection = match.Groups;
    Console.WriteLine("serial " + groupCollection[1].ToString());
}

EDIT (See @Mehrdad's helpful comments)

The original code was:

// ...

MatchCollection matches = rx.Matches(myString);
foreach (Match match in matches)
{
    GroupCollection groupCollection = match.Groups;
    Console.WriteLine("serial " + groupCollection[1].ToString());
}
peter.murray.rust
You should make sure there is actually a match before trying to access `matches[0]`. Otherwise, you'll get an `IndexOutOfRangeException`.
Mehrdad Afshari
@Mehrdad thanks. I had it in a foreach loop which was safe and then tried to simplify it. Have edited
peter.murray.rust
Yeah, if you are using it in a `foreach`, it's better **not to reference `Count`** beforehand as it'll cause the `Regex` to be evaluated immediately (as opposed to lazy evaluation you get with `foreach`)
Mehrdad Afshari
I don't think Matches does any deferred execution. Do you have a source saying otherwise?
Joren