【问题标题】:Regex Replaces the text with users case text, how to maintain the actual word case正则表达式将文本替换为用户大小写文本,如何保持实际单词大小写
【发布时间】:2015-04-15 16:15:38
【问题描述】:

我正在匹配并用<span>keyword</span>替换匹配的单词,

支持用户输入搜索关键字小写united states匹配关键字并替换

实际字符串

String str = "This is United States Of America"

Match & Replace 函数字符串被用户输入的小写匹配字符串替换后

This is united states Of America 匹配后

我想匹配和替换字符串,同时保持字符串或数据库中匹配单词的实际大小写

我为此使用以下代码。我怎样才能改变这个,以便我的要求是有意义的

    string pattern = @"(\b(?:" + Request["SearchKeyword"].ToString().Trim() + @")\b))";
    regex = new Regex(pattern, RegexOptions.IgnoreCase);
    result = regex.Replace(result, "<span class='highlight'>" + Request["SearchKeyword"].ToString() + "</span>",);

期望的输出 This is United States Of America

【问题讨论】:

    标签: c# asp.net regex


    【解决方案1】:

    您需要使用Match().Value 而不是原始请求字符串。

    这是您可以使用的代码:

    var req = "united states";
    var str = "This is United States Of America";
    var pattern = @"((?<=^\p{P}*|\p{Zs})(?:" + req.ToString().Trim() + @")(?=\p{P}*$|\p{Zs}))";
    var regx = new Regex(pattern, RegexOptions.IgnoreCase);
    var m = regx.Match(str);
    var result = string.Empty;
    if (m.Success)
       result = regx.Replace(str, "<span class='highlight'>" + m.Value + "</span>");
    

    输出:

    编辑:(以防万一)

    使用 lambda,您可以获得相同的结果:

    var regx = new Regex(pattern, RegexOptions.IgnoreCase);
    var result = regx.Replace(str, m => "<span class='highlight'>" + m.Value + "</span>");
    

    即使我们没有匹配,它也是安全的。

    【讨论】:

    • 尝试了它的魅力,样本数据需要做更多的测试,我怎样才能改变正则表达式部分,使其匹配像 lik US 这样的词,而不像 US-led,目前它也匹配 US-led 单词的一部分我如何避免在匹配单词的开头或结尾有 - 的单词
    • 您需要使用不同的边界。我会使用\s|$\s|^var pattern = @"((?&lt;=^|\s)(?:" + req.ToString().Trim() + @")(?=\s|$))";
    • 如果单词结尾像You should visit US. 这样会中断,在这种情况下它会中断,因为您使用的是\s
    • 试试这个:((?&lt;=^\p{P}*|\p{Zs})(?:US)(?=\p{P}*$|\p{Zs})) 它将允许最后(和前导以防万一)标点符号,并使用 Unicode 空格。
    【解决方案2】:

    您可以将 another overloadRegex.Replace 方法与 MatchEvaluator 一起使用

    string str = "This is United States Of America";
    string SearchKeyword = "united states";
    string pattern = @"(\b(?:" + SearchKeyword.Trim() + @")\b)";
    var regex = new Regex(pattern, RegexOptions.IgnoreCase);
    var result = regex.Replace(str, new MatchEvaluator(m => "<span class='highlight'>" + m.ToString() + "</span>"));
    

    【讨论】:

    • 我不确定从性能角度来看哪个更好,我认为您的解决方案应该更好。
    • @KnowledgeSeeker,在输入字符串string str = "This is UNITED States Of America (United States)"; 上尝试两个答案,您会发现 Regex.Replace 与 MatchEvaluator 更好(它不会改变单词!)
    猜你喜欢
    • 2022-01-09
    • 2012-07-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    相关资源
    最近更新 更多