如何从关键字列表中找到字符串中匹配的单词?

问题描述 投票:0回答:1

我有一个静态函数,它应该分析字符串,查找与预定义的关键字 lsit 匹配的单词,并向每个匹配的单词添加 Markdown 格式。然后它返回带有添加格式的字符串。

但是,无论我输入什么,我的代码都无法在字典中找到匹配项。我已经三重检查了字典中的每个条目以及输入到函数中的文本是否拼写正确。

public static string ColorizeText(string text) 
{

    List<string> keywords = new()
    {
        "Block",
        "Vulnerable",
        "Weak"
    };

    string colorizedText = string.Empty;

    foreach (string word in text.Split(' ')) 
    {
        if (keywords.Contains(word)) 
        {
            colorizedText += $"<color=yellow>{word}</color>" + " ";
        } 
        
        else 
        {
            colorizedText += word + " ";
        }
    }

    return colorizedText;
}

我假设问题点是

if
语句。无论我尝试使用
Contains
Find
等的何种变体,它都不会记录
word
keywords.

中的任何字符串相同

需要注意的一件事:我确实尝试对它检查的字符串进行硬编码,这突然起作用了,但重点是它应该是模块化的。因此,我假设问题在于

word
字符串的值与
keywords
中定义的字符串不匹配,但我不知道为什么会出现这种情况。我不习惯用字符串做很多工作,所以也许我只是错过了它们的行为方式。

我也尝试过使用子字符串和正则表达式,但我再一次对这两者都不熟悉,所以我没有太多运气。

如何让我的

if
语句识别出输入的单词存在于列表中?

c# unity-game-engine markdown
1个回答
0
投票

就我而言,我会选择正则表达式,因为它是在使用字符串时识别模式的好方法。正则表达式 (regex) 可以为匹配字符串中的单词提供更灵活、更强大的解决方案,特别是在处理大小写、标点符号和单词边界的变化时。以下是如何修改代码以使用正则表达式进行单词匹配的示例:

using System.Collections.Generic;
using System.Text.RegularExpressions;

public static string ColorizeText(string text) 
{
    List<string> keywords = new List<string>
    {
        "Block",
        "Vulnerable",
        "Weak"
    };

    string pattern = "\\b(" + string.Join("|", keywords.Select(k => Regex.Escape(k))) + ")\\b";
    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

    string colorizedText = regex.Replace(text, match => $"<color=yellow>{match.Value}</color>");

    return colorizedText;
}

说明:

  • 正则表达式模式是根据关键字动态构造的。
    \b
    是单词边界锚,确保仅匹配整个单词。
  • string.Join("|", keywords.Select(k => Regex.Escape(k)))
    为所有关键字创建正则表达式交替模式,转义它们以处理任何特殊字符。
  • RegexOptions.IgnoreCase
    使模式不区分大小写。
  • regex.Replace
    用于将输入文本中的所有匹配项替换为所需的格式。
© www.soinside.com 2019 - 2024. All rights reserved.