面试题答案
一键面试- 正则表达式写法:
- 正则表达式为
标识符:\[(.*?)\]
,其中(.*?)
用于捕获[
和]
之间的内容。 - 进一步,为了单独捕获
name:张三
和age:25
这样的组,可以使用(\w+:\w+)
这样的子表达式。完整的正则表达式为标识符:\[(?:(\w+:\w+)(?:;(\w+:\w+))*)\]
。 - 这里
(?:(\w+:\w+)(?:;(\w+:\w+))*)
是非捕获组,内部(\w+:\w+)
是捕获组,用于捕获类似name:张三
的内容,(?:;(\w+:\w+))*
用于匹配多个以;
分隔的类似内容。
- 正则表达式为
- C#代码实现过程:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "标识符:[name:张三;age:25]";
string pattern = @"标识符:\[(?:(\w+:\w+)(?:;(\w+:\w+))*)\]";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
for (int i = 1; i < match.Groups.Count; i++)
{
Console.WriteLine("捕获的组: " + match.Groups[i].Value);
}
// 替换操作示例
string replacement = "新的格式: $1, $2";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("替换结果: " + result);
}
}
}
在上述代码中:
- 首先定义了输入字符串
input
和正则表达式pattern
。 - 使用
Regex.Match
方法进行匹配,如果匹配成功,遍历match.Groups
输出捕获的组内容。 - 然后使用
Regex.Replace
方法进行替换操作,$1
和$2
等是反向引用,用于在替换字符串中使用捕获组的内容。