C# 正则表达式匹配整个单词,带特殊字符

编程入门 行业动态 更新时间:2024-10-11 15:18:42
本文介绍了C# 正则表达式匹配整个单词,带特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我搜索了一些问题,但找不到我正在寻找的确切答案.我需要在大字符串文本中搜索关键字匹配项.我正在使用 IndexOf,但是,我需要找到整个单词匹配,例如如果我搜索 Java,但文本包含 JavaScript,则不应匹配.使用 \b{pattern}\b 可以很好地工作,但是如果我搜索 C# 之类的东西,则它不起作用.

I have searched through some questions but couldn't find the exact answer i am looking for. I have a requirement to search through large strings of text looking for keywords matches. I was using IndexOf, however, i require to find whole word matches e.g. if i search for Java, but the text contains JavaScript, it shouldn't match. This works fine using \b{pattern}\b, but if i search for something like C#, then it doesn't work.

以下是我正在搜索的一些文本字符串示例:

Below is a few examples of text strings that i am searching through:

languages include Java,JavaScript,MySql,C# languages include Java/JavaScript/MySql/C# languages include Java, JavaScript, MySql, C#

显然问题出在特殊字符#"上;所以这在搜索 C++ 时也不起作用.

Obviously the issue is with the special character '#'; so this also doesn't work when searching for C++.

推荐答案

使用 Regex.Escape 转义模式并替换 context-dependent \b 单词边界与 (?<!\w)/(?!\w) 环视:

Escape the pattern using Regex.Escape and replace the context-dependent \b word boundaries with (?<!\w) / (?!\w) lookarounds:

var rx = $@"(?<!\w){Regex.Escape(pattern)}(?!\w)";

(?<!\w) 是一个否定的lookbehind,如果在当前位置之前有一个字符串的开头或一个非单词字符,则匹配失败,并且(?!\w) 是一个否定的 looahead,如果在当前位置之后立即有字符串结尾或非单词字符,则匹配失败.

The (?<!\w) is a negative lookbehind that fails the match if there is a start of string or a non-word char immediately before the current location, and (?!\w) is a negative looahead that fails the match if there is an end of string or a non-word char immediately after the current location.

更多推荐

C# 正则表达式匹配整个单词,带特殊字符

本文发布于:2023-11-02 12:08:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   特殊字符   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!