c# - 如何在 C# 中使用正则表达式从字符串中提取多个子字符串
问题描述
我从网上搜索,我只有部分解决方案,所以我提出了这个问题。
输入:
[A] this is A, and , [B] this is B, and hello , [C] this is C - From Here
我想要一个清单:
list[0] == "this is A, and"
list[1] == "this is B, and hello"
list[2] == "this is C"
list[3] == "From Here"
我发现我应该有这样的东西:
Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");
List<string> matches = pattern.Matches(input).OfType<Mathc>().Select(m => m.value).Distinct().ToList();
但它不起作用。我想问如何使它工作。谢谢。
解决方案
正则表达式是正确的,您唯一需要做的就是迭代匹配组。在您的情况下,第一组将是整个句子,因此,您可以简单地跳过第一项。
PS,当然不要忘记检查是否存在至少一个匹配结果。此外,如果此函数将多次执行,我建议您将正则表达式提取到类的静态成员中(因为性能和内存使用情况)。
private static readonly Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");
该方法的最终版本(将模式作为静态成员)如下所示。
public static List<string> GetMatches(string input)
{
var matchResult = pattern.Match(input);
if (matchResult.Length > 0)
{
return matchResult.Groups.Values
.Skip(1)
.Select(x => x.Value)
.ToList();
}
return new List<string>();
}
推荐阅读
- python - Pytest:如果另一个文件的测试失败,如何在一个文件中设置要跳过的测试
- c# - 如何使用 StreamReader.ReadAsync(内存
, 取消令牌) - javascript - Nodejs 需要异步方式的模块
- opc - 将数据写入 Matrikon OPC UA 服务器
- google-app-engine - 即使服务正在运行,gcloud app deploy 也不会终止
- assembly - 关于汇编中的命令行参数
- node.js - 如何在应用程序或功能模块加载时显式执行一些代码?
- c++ - QDialog:如何在 Windows 上启用位于父级(主窗口)后面?
- vb.net - Visual Basic 循环删除最后一个字符
- cython - 在 Cython 中定义字符串数组