2

我尝试匹配一个简单的模式 P1(空格或制表符,然后是 ##,然后是文本):

[ \t]*##\S*

但有时,我想匹配另一个模式 P2(既不是空格也不是制表符,然后是 ## 然后是文本):

[^ \t]*##\S*

当##\S* 跟随\S* 时必须使用P2

否则必须使用 P1

预期匹配结果示例:

##foo
must give
##foo

      ##foo (6 whitespaces before pattern)
must give
      ##foo (because there is some whitespaces before the pattern ##foo and not any non-whitespace characters)

foo   ##bar
must give
##bar (because there is some non-whitespace charecters before the pattern ##foobar)

foo bar   ##foobar
must give
##foobar

我尝试了lookbehind方法,但这是不可能的,因为没有固定的大小。

如果有人可以帮助我,那就太好了...

4

1 回答 1

1

使用捕获组后,您可以实现您的效果:

^(\s*##\S*)|^\S+\s*(##\S*)

然后像

     ## foo

将由第一个备选方案匹配,并且可以从第一个捕获组中获得结果,而

foo  ## bar

将被第二个备选方案匹配,并且可以从第二个捕获组中获得“## bar”。

于 2013-10-22T10:28:12.233 回答