Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of java.util.regex?

Tags:

java

c#

regex

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.)

like image 273
peter.murray.rust Avatar asked Oct 17 '09 16:10

peter.murray.rust


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.


2 Answers

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

like image 66
mmx Avatar answered Sep 27 '22 18:09

mmx


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());
}
like image 38
peter.murray.rust Avatar answered Sep 27 '22 16:09

peter.murray.rust