Joh*_*ara 7 c# regex asp.net string
我有一种方法可以用来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...
}
Run Code Online (Sandbox Code Playgroud)
此版本对以前的版本进行了改进,因为它确实允许单词以任何顺序进行匹配,但是由于删除了间距并用管道替换了间距,因此最终输出中会出现间距问题。
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...
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,需要在每个单词周围保留间距。下面的伪示例显示了我正在尝试执行的操作。
重新加入单词模式以产生将用于匹配的模式
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...
}
Run Code Online (Sandbox Code Playgroud)注意:可能有更好的方法来处理单词边界间距,但我不是正则表达式专家。
我正在寻找一些帮助/建议来使用分割数组,包装它,然后以最简洁的方式重新加入它。
您需要将所有替代方案包含在一个非捕获组中,(?:...|...)。此外,为了进一步解决最终的问题,我建议将单词边界替换为它们的环视明确等价物,(?<!\w)...(?!\w)。
这是一个有效的 C# 片段:
var text = "there are big widgets in this phrase blue widgets too";
var words = "big blue widgets";
var pattern = $@"(\s*(?<!\w)(?:{string.Join("|", words.Split(' ').Select(Regex.Escape))})(?!\w)\s*)";
var result = string.Concat(Regex.Split(text, pattern, RegexOptions.IgnoreCase).Select((str, index) =>
index % 2 == 0 && !string.IsNullOrWhiteSpace(str) ? $"<b>{str}</b>" : str));
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
笔记
words.Split(' ').Select(Regex.Escape)- 用words空格分割文本并正则表达式转义每个项目string.Join("|",...)|重新构建插入项目之间的字符串(?<!\w)负lookbehind 匹配前面没有紧跟着单词char 的位置,而(?!\w)负lookahead 匹配后面没有紧跟着单词char 的位置。| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |