📅  最后修改于: 2023-12-03 14:39:47.244000             🧑  作者: Mango
正则表达式是一种用来匹配和处理字符串的强大工具,在C#中也得到了广泛的应用。在本文中,我们将介绍如何使用C#正则表达式查找括号之间的数字。
System.Text.RegularExpressions.Regex
命名空间中的静态方法Match
来从字符串中匹配符合正则表达式条件的子字符串。该方法的参数有两个,分别是要匹配的字符串和正则表达式。string input = "abcdefg(123)hijklmn(456)opqrstu(789)";
string pattern = @"\([\d]+\)";
MatchCollection matches = Regex.Matches(input, pattern);
该代码用正则表达式@"\([\d]+\)"
来匹配字符串input
中的括号内数字。其中:
\(
表示匹配左括号,\)
表示匹配右括号,\(
和\)
之间的内容表示要匹配的内容,即“括号内的数字”。[\d]+
表示匹配连续的数字,其中\d
表示数字,+
表示匹配一个或多个\d
。MatchCollection
对象中的每一个Match
对象,即可得到所有匹配的结果。Match
对象中包含了匹配到的字符串本身,以及匹配到的字符串在原始字符串中的起始位置。foreach (Match match in matches)
{
Console.WriteLine(match.Value.Trim('(', ')'));
}
该代码遍历了所有匹配的Match
对象,并打印出匹配到的数字字符串。其中:
match.Value
表示匹配到的字符串本身,需要使用Trim
方法去掉两侧的括号。foreach
循环用来遍历所有的Match
对象。使用C#正则表达式可以非常方便地查找括号之间的数字。对于需要在程序中对字符串进行处理的场景,正则表达式是一个非常强大和实用的工具。
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string input = "abcdefg(123)hijklmn(456)opqrstu(789)";
string pattern = @"\([\d]+\)";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value.Trim('(', ')'));
}
}
}
}