【问题标题】:How to extract a whole word from a sentence by a specific fragment in C#?如何通过C#中的特定片段从句子中提取整个单词?
【发布时间】:2021-08-28 22:36:06
【问题描述】:

如何在字符串类型的句子中获取整个单词? \

例如,如果给定的字符串是:

The app has been updated to 88.0.1234.141 which contains a number of fixes and improvements.

我想通过特定片段“.0.”获取单词 88.0.1234.141
如何获取包含“.0.”的每个单词?有没有一种快速的方法来做到这一点,比如 Regex 而不是使用嵌套循环?

【问题讨论】:

  • string input = "该应用已更新至 88.0.1234.141,其中包含许多修复和改进。";字符串模式 = @"[.\d]+\.0\.[.\d]+"; MatchCollection 匹配 = Regex.Matches(input, pattern); string[] 索引 = matches.Cast().Select(x => x.Value).ToArray();

标签: c# .net regex string text-segmentation


【解决方案1】:

您可以使用regular expression 来解决此问题。因此,您可以使用一个简单的方法:将每个包含.0. 的单词放在里面。每个单词都应该被一个空格包围。结果的表达式可能如下所示:

这是一个已实现的表达式示例:

string input = "The app has been updated to 88.0.1234.141 which contains a number of fixes and improvements.";
MatchCollection matches = Regex.Matches(input, @"[^-\s]*\.0\.[^-\s]*");
foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

输出将是

88.0.1234.141

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多