【发布时间】:2019-09-26 00:24:39
【问题描述】:
我有一个使用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... }
注意:处理单词边界间距可能有更好的方法,但我不是正则表达式专家。
我正在寻找一些帮助/建议来获取拆分数组,将其包装,然后以最简洁的方式重新加入。
【问题讨论】:
-
也许 - 如果您有 1 个空格分隔的单词,仅由单词字符组成 - 只需使用
var phrasePattern = $@"\s*\b(?:{wordsToExclude.Replace(" ", "|")})\b\s*"; -
请问原来的问题是什么?假设,给你一个短语,例如
"The quick brown fox (not wolf or cat) runs, jumps over a lazy (!) dog."和 要排除的单词,例如{"wolf", "over", "the"}。那么期望的结果是什么? -
正如我所说,我不是正则表达式专家,但下面的代码似乎只是 V2 示例的变体 - 如果我错了,请纠正我。
-
@JohnOhara 我在顶部评论中建议的一段代码是您的 V2 示例的修复。
-
@DmitryBychenko - 这是大蓝色小部件的示例,“大小部件很棒,但如果蓝色更好” - 输出最终将使用正则表达式附加 html “蓝色小部件 很棒但更好 大”