正则表达式\b,但在 c# 中不仅仅包含字母数字字符 [英] Regular expressions \b but with not just alphanumeric characters in c#

查看:19
本文介绍了正则表达式\b,但在 c# 中不仅仅包含字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要与 \b 相同的功能,但需要其他字符.

I want the same functionality as \b but with other characters.

在 C# 中,我想要类似

In C#, I want to have something like

string str = "\\b" + Regex.Escape(string) + "\\b");

但是我有一些Regex.Escape("@(Something")将在字符串 Typing @(Something to you.

However I have some so Regex.Escape("@(Something") will find it in the string Typing @(Something to you.

推荐答案

您遇到的问题与 \b 词边界 是上下文相关的,并且 \b\(abc\b 将匹配 (abcx(abc) 中,但不在 :(abc) 中(\b\( 表示 ().

The problem you experience is related to the fact that \b word boundary is context dependent, and \b\(abc\b will match (abc in x(abc) but not in :(abc) (\b\( means there must be a word char before ().

要匹配任何未用字符字符括起来的字符串,请使用

To match any string that is not enclosed with word chars use

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

正则表达式演示.

这里,(?<!\w) 是一个负向后视,将确保当前位置的左边没有字 char,而 (?!\w) 负向前瞻将确保当前位置右侧没有字字符.

Here, (?<!\w) is a negative lookbehind that will make sure there is no word char immediately to the left of the current location, and (?!\w) negative lookahead will make sure there is no word char immediately to the right of the current location.

其他自定义词"边界:

  • 空白词边界:var pattern = $@"(?<!\S){Regex.Escape(string)}(?!\S)";//用空格括起来时匹配
  • 单词和符号边界(如果你不想在c++中找到c):var pattern = $@"(?<![\w\p{S}]){Regex.Escape(string)}(?![\w\p{S}])";

这篇关于正则表达式\b,但在 c# 中不仅仅包含字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆