为什么\b不使用正则表达式.NET词相匹配 [英] Why \b does not match word using .net regex
问题描述
要定期复查我expresions阅读本教程 。不管怎么说该教程提到 \b
字边界(\w和\W字符之间)匹配。该教程还给出了一个链接,您可以安装快报(程序创建正则表达式时,可以帮助)。
To review regular expresions I read this tutorial. Anyways that tutorial mentions that \b
matches a word boundary (between \w and \W characters). That tutorial also gives a link where you can install expresso (program that helps when creating regular expressions).
所以,我创建了我在快报的正则表达式,我也inded得到匹配。现在,当我同样的正则表达式复制到Visual Studio我没有得到匹配。请看下图:
So I have created my regular expressions in expresso and I do inded get a match. Now when I copy the same regex to visual studio I do not get a match. Take a look:
为什么我没有得到匹配?在即时窗口中我显示可变输出的内容。在快报我得到了根火柴,在Visual Studio中我不知道。为什么?
Why am I not getting a match? in the immediate window I am showing the content of variable output. In expresso I do get a match and in visual studio I don't. why?
推荐答案
C#编译器被拦截在您的字符串的\b并将其转换为ASCII退格字符。你需要让你的字符串逐字(前缀与在符号)左右反斜杠传递给正则表达式,像这样的双逃脱'B':
The C# compiler is intercepting the \b in your string and converting it into an ASCII backspace character. You need to make your string verbatim (prefix with an at-symbol) or double-escape the 'b' so the backslash is passed to RegEx like so:
@"\bCOMPILATION UNIT";
或
"\\bCOMPILATION UNIT"
我会说的.NET正则表达式文档没有明确这一点。我花了,而在第一次过这个号码
I'll say the .NET RegEx documentation does not make this clear. It took me a while to figure this out at first too.
趣味-的事实:在 \r
和 \\\
(分别是回车和换行)字符和其他一些人被两个正则表达式和C#语言识别,所以最终的结果是一样的,甚至如果编译串是不同的。
Fun-fact: The \r
and \n
characters (carriage-return and line-break respectively) and some others are recognized by both RegEx and the C# language, so the end-result is the same, even if the compiled string is different.
这篇关于为什么\b不使用正则表达式.NET词相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!