正则表达式匹配# [英] Regular expression to match a #
问题描述
我正在尝试使用正则表达式来匹配包含#
的字符串(基本上我正在寻找#include ...)
我似乎无法写出与之匹配的正则表达式。
我的(可能天真)方法是:p = re.compile(r''\ #include\b)
我也试过p = re.compile(r''\\# include \ b)徒劳地试图在#
之前使用
a反斜杠作为转义字符以上所有都没有返回匹配像#include<这样的字符串; stdio>" ;.
我知道#用于评论,因此我试图逃避它...
任何建议关于如何获得正则表达式来找到#?
谢谢
Hi,
I''m trying to use a regular expression to match a string containing a #
(basically i''m looking for #include ...)
I don''t seem to manage to write a regular expression that matches this.
My (probably to naive) approach is: p = re.compile(r''\b#include\b)
I also tried p = re.compile(r''\b\#include\b) in a futile attempt to use
a backslash as escape character before the #
None of the above return a match for a string like "#include <stdio>".
I know a # is used for comments, hence my attempt to escape it...
Any suggestion on how to get a regular expression to find a #?
Thanks
推荐答案
>我的(可能是天真的)方法是:p = re.compile(r''\ ## include \b)
我认为你的问题是\b在开始。 \b匹配单词中断
(定义为\w\W或\ W\w)。如果前面的字符是\w(即[A-Za-z0-9_],也许是
$ b $),那么在#
之前只会有一个单词中断b一些其他字符,具体取决于您的语言环境)。
但是,在include之后的\b正是你想要的。
-
我已经选择了婴儿房间的主题并做了其他的
东西。我决定让Jon有这个。
- Jamie Cusack(荷兰人),她的丈夫Jon
终于和她谈了让他给他们的儿子命名为Jon 2.0 >
> My (probably to naive) approach is: p = re.compile(r''\b#include\b)
I think your problem is the \b at the beginning. \b matches a word break
(defined as \w\W or \W\w). There would only be a word break before the #
if the preceding character were a \w (that is, [A-Za-z0-9_], and maybe
some other characters depending on your locale).
However, the \b after the "include" is exactly what you want.
--
I had picked out the theme of the baby''s room and done other
things. I decided to let Jon have this.
- Jamie Cusack (of the Netherlands), whose husband Jon
finally talked her into letting him name their son Jon 2.0
谢谢,
这就行了......
Thanks,
That did the trick...
Dan写道:
Dan wrote:
我的(可能是天真的)方法是:p = re.compile(r''\ b #include\b)
My (probably to naive) approach is: p = re.compile(r''\b#include\b)
我认为你的问题是开头的\b。 \b匹配单词分隔
(定义为\w\W或\ W\w)。如果前面的字符是\w(即[A-Za-z0-9_],可能还有其他字符取决于你的语言环境,那么#
之前只会有一个单词分隔符但是,
然后,在包括之后的\b正是你想要的。
I think your problem is the \b at the beginning. \b matches a word break
(defined as \w\W or \W\w). There would only be a word break before the #
if the preceding character were a \w (that is, [A-Za-z0-9_], and maybe
some other characters depending on your locale).
However, the \b after the "include" is exactly what you want.
所以OP可能想要''\ B''与''\ b''完全相反的开头
字符串,即仅匹配#,如果它没有字母开头。
或者C风格#includes搜索r''^ \ s *#\ * * include \ b''。
So the OP probably wanted ''\B'' the exact opposite of ''\b'' for the start of
the string, i.e. only match the # if it is NOT preceded by a wordbreak.
Alternatively for C style #includes search for r''^\s*#\s*include\b''.
这篇关于正则表达式匹配#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!