开发者

Regular expression of 2 tags open and close and many lines

I'm trying to match this block 开发者_如何学编程here

/code\

int foo(string $bar, int $bleh); Simple function!

bool is_even(mixed $var); Checks if a variable is even.

\code/

my pattern is "/code\\(.*?)\code/"

yet no matches found!

Okay it's very hard to show what I mean in stackoverflow due to all the restrictions on html.

But code tags are basically HTML tags with opener and closer tag.

does regex not handle multiple lines? yes I do have multi-line flag triggered

Thanks


In most regex implementations, multi-line mode with the m modifier does not let the . match line breaks, but causes the ^ to match the start of a line and the $ match the end of a line.

What you need is to enable dot-all mode by adding the s modifier. And if your language's regex implementation does not support that modifier (JavaScript does't, if memory serves me right), you can mimic this using [\s\S] instead of . (DOT).

Be aware that you will get in trouble matching stuff like:

nested tags:

/code\

/code\

...

\code/

\code/

(matched text: /code\ /code\ ... \code/)

or commented tags:

/code\

...

<!-- \code/ -->

\code/

(matched text: /code\ ... <!-- \code/)


Use the "global" option to tell the re engine to treat the whole string as one line.


You need to double up one of your backslashes:

/code\\(.*?)\\code/
            ^--- right here
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜