【问题标题】:Use C# to reparse a string already containing asterisk character replacements使用 C# 重新解析已经包含星号字符替换的字符串
【发布时间】:2021-06-28 10:42:19
【问题描述】:

我收到了对此处提出的先前问题的非常有用的回复。

Use C# to surround phrases in a string with asterisk characters from a dictionary of phrases

我现在发布针对特定问题的后续问题。

我最初查询的基本前提是我有一组单词和短语,如下所示。

  • 面粉
  • 小麦粉
  • 坚果
  • 坚果

处理一串文本后,如下所示。

"Salt, Water, Wheat Flour, Palm Oil, Nuts, Tree Nuts"

我的目标是得到一个如下所示的字符串(即字典中的单词和短语用星号字符包围,最长的短语优先)。

"Salt, Water, *Wheat Flour*, Palm Oil, *Nuts*, Tree *Nuts*"

通过使用 Dmitry Bychenko 提供的以下正则表达式模式可以实现上述目标。

  string pattern = @"\b(?<!\*)(?:" + string.Join("|", words
    .Distinct()
    .OrderByDescending(chunk => chunk.Length)
    .Select(chunk => Regex.Escape(chunk))) + @")(?!\*)\b";

我有一个关于我正在处理的字符串何时已被处理的具体问题。

假设我有一个已经被处理过的字符串,如下所示。

"Salt, Water, *Wheat Flour*, Palm Oil, *Nuts*, Tree *Nuts*"

如果我想在上面的字符串中替换的单词数组现在包含一个更具体的短语,例如“Tree Nuts”,是否有一个正则表达式可以检测到以下短语应该被替换?

"Tree *Nuts*"

即这部分字符串应更新为以下内容。

"*Tree Nuts*"

【问题讨论】:

  • 在重新处理字符串之前删除所有星号。

标签: c# regex string replace


【解决方案1】:

作为一种快速的解决方案,我建议实施两级替换。

首先,让我们删除“错误的”*,即将任何*word* 变成word

  string[] words = new string[] {
    "Flour",
    "Wheat Flour",
    "Nut",
    "Nuts",
    "Tree Nuts"
  };

  string removePattern = @"(?:" + string.Join("|", words
    .Distinct()
    .OrderByDescending(chunk => chunk.Length)
    .Select(chunk => $@"\*{Regex.Escape(chunk)}\*")) + @")";

所以给定 text* 我们可以清除它:

  string text = "Salt, Water, *Wheat Flour*, Palm Oil, *Nuts*, Tree *Nuts*";

  // unwanted * removed: 
  // "Salt, Water, Wheat Flour, Palm Oil, Nuts, Tree Nuts" 
  string cleared = Regex.Replace(text, removePattern, m => m.Value.Trim('*'));

然后(第二阶段)一切照旧:

  string pattern = @"\b(?<!\*)(?:" + string.Join("|", words
    .Distinct()
    .OrderByDescending(chunk => chunk.Length)
    .Select(chunk => Regex.Escape(chunk))) + @")(?!\*)\b";

  string result = Regex.Replace(cleared, pattern, m => "*" + m.Value + "*");

【讨论】:

  • 再次感谢您!
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2021-08-19
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 2017-08-04
相关资源
最近更新 更多