我有一个使用的方法Regex
寻找文本中的模式string
。它可以工作,但不足以继续下去,因为它需要文本出现在确切的顺序,而不是将短语视为一组单词。
public static string HighlightExceptV1(this string text, string wordsToExclude)
{
// Original version
// wordsToExclude usually consists of a 1, 2 or 3 word term.
// The text must be in a specific order to work.
var pattern = $@"(\s*\b{wordsToExclude}\b\s*)";
// Do something to string...
}
这个版本对以前的版本进行了改进,因为它确实允许单词以任何顺序匹配,但是它导致一些间距问题在最终输出中,因为间距被删除并替换为管道。
public static string HighlightExceptV2(this string text, string wordsToExclude)
{
// This version allows the words to be matched in any order, but it has
// flaws, in that the natural spacing is removed in some cases.
var words = wordsToExclude.Replace(' ', '|');
var pattern = $@"(\s*\b{words}\b\s*)";
// Example phase: big blue widget
// Example output: $@"(\s*\bbig|blue|widget\b\s*)"
// Do something to string...
}
理想情况下,每个单词周围需要保留间距。下面的伪示例显示了我正在尝试做的事情。
- 将原始短语拆分为单词
- 将每个单词包装在正则表达式模式中,以保留空间
当匹配时
-
重新连接单词模式以生成将用于的模式
匹配
public static string HighlightExceptV3(this string text, string wordsToExclude)
{
// The outputted pattern must be dynamic due to unknown
// words in phrase.
// Example phrase: big blue widgets
var words = wordsToExclude.Replace(' ', '|');
// Example: big|blue|widget
// The code below isn't complete - merely an example
// of the required output.
var wordPattern = $@"\s*\b{word}\b\s*";
// Example: $@"\s*\bwidget\b\s*"
var phrasePattern = "$({rejoinedArray})";
// @"(\s*\bbig\b\s*|\s*\bblue\b\s*|\s*\bwidget\b\s*)";
// Do something to string...
}
注意:可能有更好的方法来处理单词边界间距,但我不是正则表达式专家。
我正在寻找一些帮助/建议来获取分割数组,包装它,然后以最简洁的方式重新加入它。