I am converting Java code to C# and need to replace the use of Java's regex. A typical use is
我正在将Java代码转换为c#,需要替换使用Java的regex。一个典型的使用
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.
编辑:我现在已经添加了c#的代码作为一个答案。
EDIT: Here is a tutorial on the use of the actual expressions.
编辑:这里有一个关于实际表达式使用的教程。
EDIT: Here is a useful comparison of C# and Java (and Perl.)
编辑:这里有一个关于c#和Java(以及Perl)的有用的比较。
2 个解决方案
#1
13
System.Text.RegularExpressions.Regex
class is the .NET Framework equivalent. The MSDN page I linked to contains a simple example.
包含。Regex类是。net框架等效的。我链接到的MSDN页面包含一个简单的示例。
#2
5
I created the C# equivalent of the Java code in the question as:
我创建了c#等价于问题中的Java代码:
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)
编辑(参见@Mehrdad的有用评论)
The original code was:
原始代码是:
// ...
MatchCollection matches = rx.Matches(myString);
foreach (Match match in matches)
{
GroupCollection groupCollection = match.Groups;
Console.WriteLine("serial " + groupCollection[1].ToString());
}
#1
13
System.Text.RegularExpressions.Regex
class is the .NET Framework equivalent. The MSDN page I linked to contains a simple example.
包含。Regex类是。net框架等效的。我链接到的MSDN页面包含一个简单的示例。
#2
5
I created the C# equivalent of the Java code in the question as:
我创建了c#等价于问题中的Java代码:
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)
编辑(参见@Mehrdad的有用评论)
The original code was:
原始代码是:
// ...
MatchCollection matches = rx.Matches(myString);
foreach (Match match in matches)
{
GroupCollection groupCollection = match.Groups;
Console.WriteLine("serial " + groupCollection[1].ToString());
}