函数/正则表达式匹配较大字符串中的字符串部分&突出显示部分

时间:2017-03-10 19:05:25

标签: c# regex string

我正在尝试构建一个带有搜索字符串并匹配较大字符串中的部分的函数。突出他们。见下面的例子:

原始字符串:由于飞机上的空间有限,我保证,检查行李不收费,我可以继续填写所有托运行李表您。

要搜索的文字&突出显示:免费,我填写表格

期望的结果:由于飞机上的空间有限,我向您保证,检查行李将会有 免费 ,我 可以继续 填写 所有 托运行李 表格

我可以搜索完整的字符串或使用子字符串一次搜索一个单词,但两者都不会产生所需的结果。诀窍可能是以某种方式递归搜索从完整字符串开始,并逐渐将其分解为更小的片段,直到部分匹配。有几个假设:

  • 搜索必须尽可能贪婪,即在尝试匹配较小的部分或单个单词之前匹配字符串的较大部分。
  • 搜索将始终在找到任何匹配后前进,即如果在位置x找到前2个单词,则单词3和4将始终位于x之后,而不是x之前。

希望这是有道理的。谁能指出我正确的方向?我搜索过该网站,但没有发现任何类似于我正在寻找的内容。

由于

1 个答案:

答案 0 :(得分:0)

如果这有助于您,请告诉我。它没有使用正则表达式来查找字符串,只需IndexOf

首先将要突出显示的单词Tuple表示单词的起始索引和结束索引。

它使用前缀和后缀来突出显示文本(这里是:html标签)。

static void Main(string[] args)
{
    var input = "Since there is limited overhead space on the plane, I assure you, there will be no fee for checking the bags, I can go ahead and fill out all the checked baggage forms for you";
    var searchExpression = "no fee, I fill out the forms";

    var highlightedInput = HighlightString(input, searchExpression, "<b>", "</b>");

    Console.WriteLine(highlightedInput);
    Console.ReadLine();
}

public static IEnumerable<Tuple<int, int>> GetHighlights(string input, string searchExpression)
{
    var splitIntoWordsRegex = new Regex(@"\W+");
    var words = splitIntoWordsRegex.Split(searchExpression);
    return GetHighlights(input, words);
}

public static IEnumerable<Tuple<int, int>> GetHighlights(string input, IEnumerable<string> searchExpression)
{
    var highlights = new List<Tuple<int, int>>();

    var lastMatchedIndex = 0;
    foreach (var word in searchExpression)
    {
        var indexOfWord = input.IndexOf(word, lastMatchedIndex,  StringComparison.CurrentCulture);
        var lastIndexOfWord = indexOfWord + word.Length;

        highlights.Add(new Tuple<int, int>(indexOfWord, lastIndexOfWord));

        lastMatchedIndex = lastIndexOfWord;
    }

    return highlights;
}

public static string HighlightString(string input, string searchExpression, string highlightPrefix, string highlightSufix)
{
    var highlights = GetHighlights(input, searchExpression).ToList();

    var output = input;
    for (int i = 0, j = highlights.Count; i<j; i++)
    {
        int diffInputOutput = output.Length - input.Length;
        output = output.Insert(highlights[i].Item1 + diffInputOutput, highlightPrefix);

        diffInputOutput = output.Length - input.Length;
        output = output.Insert(highlights[i].Item2 + diffInputOutput, highlightSufix);
    }

    return output;
}

==================编辑======================

为了减少突出显示的最小/最大索引,您可以使用以下代码。虽然不是最漂亮的,但是做到了。

它获取一个单词的所有索引(感谢Finding ALL positions of a substring in a large string in C#)。将它们添加到highlights,然后操纵此集合以保持关闭匹配所需的内容。

public static IEnumerable<Tuple<int, int>> GetHighlights(string input, IEnumerable<string> searchExpression)
{
    var highlights = new List<Tuple<string, int, int>>();

    // Finds all the indexes for 
    // all the words found.
    foreach (var word in searchExpression)
    {
        var allIndexesOfWord = AllIndexesOf(input, word, StringComparison.InvariantCultureIgnoreCase);
        highlights.AddRange(allIndexesOfWord.Select(index => new Tuple<string, int, int>(word, index, index + word.Length)));
    }

    // Reduce the scope of the highlights in order to 
    // keep the indexes as together as possible.
    var firstWord = searchExpression.First();
    var firstWordIndex = highlights.IndexOf(highlights.Last(x => String.Equals(x.Item1, firstWord)));

    var lastWord = searchExpression.Last();
    var lastWordIndex = highlights.IndexOf(highlights.Last(x => String.Equals(x.Item1, lastWord)));

    var sanitizedHighlights = highlights.SkipWhile((x, i) => i < firstWordIndex);
    sanitizedHighlights = sanitizedHighlights.TakeWhile((x, i) => i <= lastWordIndex);

    highlights = new List<Tuple<string, int, int>>();
    foreach (var word in searchExpression.Reverse())
    {
        var lastOccurence = sanitizedHighlights.Last((x) => String.Equals(x.Item1, word));
        sanitizedHighlights = sanitizedHighlights.TakeWhile(x => x.Item3 < lastOccurence.Item2);
        highlights.Add(lastOccurence);
    }

    highlights.Reverse();

    return highlights.Select(x => new Tuple<int, int>(x.Item2, x.Item3));
}

public static List<int> AllIndexesOf(string str, string value, StringComparison comparison)
{
    if (String.IsNullOrEmpty(value))
        throw new ArgumentException("the string to find may not be empty", "value");

    List<int> indexes = new List<int>();
    for (int index = 0; ; index += value.Length)
    {
        index = str.IndexOf(value, index, comparison);
        if (index == -1)
            return indexes;
        indexes.Add(index);
    }
}

使用此代码和文字:

"No, about the fee, since there is limited overhead space on the plane, I assure you, there will be no fee for checking the bags, I can go ahead and fill out all the checked baggage forms for you."

我得到了以下结果:

不,关于费用,因为飞机上的空间有限,我保证,没有 费用来检查行李,可以继续填写 所有 托运行李表格

=============================================== =======

编辑2 使用正则表达式方法,获得之前尝试获得的经验。
请注意,如果找不到表达式中的每个单词,则不会找到任何高亮显示。

public static IEnumerable<Tuple<int,int>> GetHighlights(string expression, string search)
{
    var highlights = new List<Tuple<string, int, int>>();

    var wordsToHighlight = new Regex(@"(\w+|[^\s]+)").
        Matches(search).
        Cast<Match>().
        Select(x => x.Value);

    foreach(var wordToHighlight in wordsToHighlight)
    {
        Regex findMatchRegex = null;
        if (new Regex(@"\W").IsMatch(wordToHighlight))
            findMatchRegex = new Regex(String.Format(@"({0})", wordToHighlight), RegexOptions.IgnoreCase);  // is punctuation
        else
            findMatchRegex = new Regex(String.Format(@"((?<!\w){0}(?!\w))", wordToHighlight), RegexOptions.IgnoreCase); // si word

        var matches = findMatchRegex.Matches(expression).Cast<Match>().Select(match => new Tuple<string, int, int>(wordToHighlight, match.Index, match.Index + wordToHighlight.Length));

        if (matches.Any())
            highlights.AddRange(matches);
        else
            return new List<Tuple<int, int>>();
    }

    // Reduce the scope of the highlights in order to 
    // keep the indexes as together as possible.
    var firstWord = wordsToHighlight.First();
    var firstWordIndex = highlights.IndexOf(highlights.Last(x => String.Equals(x.Item1, firstWord)));

    var lastWord = wordsToHighlight.Last();
    var lastWordIndex = highlights.IndexOf(highlights.Last(x => String.Equals(x.Item1, lastWord)));

    var sanitizedHighlights = highlights.SkipWhile((x, i) => i < firstWordIndex);
    sanitizedHighlights = sanitizedHighlights.TakeWhile((x, i) => i <= lastWordIndex);

    highlights = new List<Tuple<string, int, int>>();
    foreach (var word in wordsToHighlight.Reverse())
    {
        var lastOccurence = sanitizedHighlights.Last((x) => String.Equals(x.Item1, word));
        sanitizedHighlights = sanitizedHighlights.TakeWhile(x => x.Item3 < lastOccurence.Item2);
        highlights.Add(lastOccurence);
    }

    highlights.Reverse();

    return highlights.Select(x => new Tuple<int, int>(x.Item2, x.Item3));
}

值得注意的是,这种方法现在负责标点符号。找到了以下结果。

<强>输入:
No, about the fee, since there is limited overhead space on the plane, I assure you, there will be no fee for checking the bags, I can go ahead and fill out all the checked baggage forms for you.

搜索:
no fee, I fill out the forms

输出:
不,关于费用,因为飞机上的空间有限,我保证,没有 费用来检查行李 可以继续填写 所有 托运行李表格点。

<强>输入:
When First Class Glass receives your call, we will assign a repair person to visit you to assist.

搜索:
we assign a repair person

输出:
当头等舱玻璃接到您的电话时,我们指定 a 维修 拜访你协助。