📌  相关文章
📜  c# 正则表达式查找括号之间的数字 - C# (1)

📅  最后修改于: 2023-12-03 14:39:47.244000             🧑  作者: Mango

C# 正则表达式查找括号之间的数字

正则表达式是一种用来匹配和处理字符串的强大工具,在C#中也得到了广泛的应用。在本文中,我们将介绍如何使用C#正则表达式查找括号之间的数字。

步骤
  1. 使用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
  1. 遍历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('(', ')'));
            }
        }
    }
}