2013-10-22 63 views
2

我嘗試(文字空格或製表符,然後再##)匹配一個簡單的模式P1:有條件匹配PCRE正則表達式:各種大小的lookbehind如何?

[ \t]*##\S* 

但有時候,我想,以配合另一模式P2(既不空格,也不選項卡,然後再##文本):

[^ \t]*##\S* 

P2時,必須使用## \ S *遵循\ S *

P1必須以其他方式使用

預期匹配資源的

例子ults:

##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方法,但這是不可能的,因爲沒有固定的大小。

這將是非常好的,如果有人可以幫助我...

+0

你想捕捉所有必須提供的字符串嗎? – anubhava

回答

1

可以使用捕捉組後實現的你在做什麼的效果:

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

然後像

 ## foo 

將與第一個替代項匹配,並且結果可以從第一個捕獲組獲得,而

foo ## bar 

將與第二個備選方案匹配,並且可以從第二個捕獲組獲得「## bar」。

+1

太棒了!謝謝Stuart!最終正則表達式是:^(\ s * ## \ S *)|^\ S +(?:\ s | \ S)*(## \ S *) – Nicolas

相關問題