面试题答案
一键面试- 使用正则表达式提取数字:
在C#中,可以使用
Regex
类结合正则表达式来提取字符串中的数字部分。正则表达式\d+
可以匹配一个或多个数字。示例代码如下:using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, 123 World, 456"; MatchCollection matches = Regex.Matches(input, @"\d+"); foreach (Match match in matches) { Console.WriteLine(match.Value); } } }
- 捕获组的作用:
- 捕获组是正则表达式中用圆括号括起来的部分。在这个例子中,如果写成
(\d+)
,就是一个捕获组。捕获组的作用是可以将匹配到的部分单独提取出来,并进行分组编号。编号从1开始,第0组代表整个匹配的字符串。 - 捕获组在更复杂的匹配场景中非常有用,比如在匹配邮箱地址
([\w -]+(\.[\w -]+)*)@((\[[0 - 9]{1,3}\.[0 - 9]{1,3}\.[0 - 9]{1,3}\.)|(([\w -]+\.)+))([a-zA - Z]{2,4}|[0 - 9]{1,3})(\]?)
时,可以通过捕获组分别获取邮箱的用户名部分、域名部分等。
- 捕获组是正则表达式中用圆括号括起来的部分。在这个例子中,如果写成
- 在代码中获取捕获组的内容:
当使用捕获组时,
Match
对象的Groups
属性可以获取捕获组的集合。示例代码如下:
在上述代码中,using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, 123 World, 456"; Match match = Regex.Match(input, @"(?<number>\d+)"); if (match.Success) { Group numberGroup = match.Groups["number"]; Console.WriteLine("捕获组'number'的值: " + numberGroup.Value); } } }
(?<number>\d+)
定义了一个命名捕获组number
,通过match.Groups["number"]
可以获取该捕获组匹配到的内容。如果是未命名的捕获组,可以通过索引(从1开始)来获取,如match.Groups[1]
。