【问题标题】:Search for a word or a similar word using regex C# [closed]使用正则表达式 C# 搜索单词或类似单词 [关闭]
【发布时间】:2020-09-26 11:42:13
【问题描述】:

我有文本,我想搜索一个词或类似的词(狐狸/狐狸)。当我在代码中设置单词时它的工作,但是当我想从文本框中获取它时不起作用

这项工作很完美

 var rx = new Regex("fox(es)?", RegexOptions.Compiled | RegexOptions.IgnoreCase);

但是当我用变量改变它时不起作用,我不知道要修复它

 var word = textBox2.ToString();
 var rx = new Regex(word+"(es)?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var content = @"Foxes are omnivorous mammals belonging to several genera 
of the family Canidae. Foxes have a flattened skull, upright triangular ears, 
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every 
continent except Antarctica. By far the most common and widespread species of 
fox is the red fox.";

            var word = textBox2.ToString();
            var rx = new Regex(word+"(es)?", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            Match match = rx.Match(content);

            while (match.Success)
            {
                Console.WriteLine($"{match.Value} at index {match.Index}");
                match = match.NextMatch();
            }

【问题讨论】:

  • textBox2.ToString() 不返回文本框内容。要获取文本框内容,请使用textBox2.Text
  • 哦,是的,我现在看到了。我还有其他问题,如果我想在搜索词为 fox 时显示 foxessm、foxessss 等词,你知道如何更改正则表达式
  • 只用搜索字符串"fox"?如果你不关心它的结尾,它甚至不需要是一个正则表达式。 content.Contains(textBox2.Text, StringComparison.OrdinalIgnoreCase) 应该够了
  • @Xerillio 是的,但是当我使用 contains 时,我不知道如何获取单词和位置,我只能取第一个和最后一个位置

标签: c# regex search


【解决方案1】:

只需使用 IndexOf 查找您的单词的位置:

var index = content.IndexOf(textBox2.Text, StringComparison.OrdinalIgnoreCase);

如果你想看到更多的出现,设置一个 startIndex:

//List of all indexes
var indexes = new List<int>();    


int nextIndex = index;

//While it finds new occurrences
while(nextindex != -1)
{
    //adds index to the List
    indexes.Add(nextIndex);

    //searches for new occurrence
    var nextIndex= content.IndexOf(textBox2.Text, indexes.Last() + 1, StringComparison.OrdinalIgnoreCase);    
}

【讨论】:

  • 它的工作,但我有最后一个问题,你知道如何更改文本中搜索词的背景颜色(这是方法 .SelectionBackColor = Color.Yellow;),但我不知道如何使用它
  • 我认为不可能这样,因为您在一个文本框中。您必须创建多个文本框,因为您只能更改整个文本框的背景颜色
猜你喜欢
  • 2012-03-10
  • 2020-01-25
  • 1970-01-01
  • 2015-03-16
  • 2012-10-17
  • 2012-03-28
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多