簡體   English   中英

條件匹配PCRE正則表達式:如何進行各種尺寸的回溯?

[英]Conditional matching PCRE regex: how do a lookbehind with various size?

我嘗試匹配一個簡單的模式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方法,但是因為沒有固定的大小,所以這是不可能的。

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

使用捕獲組后,您可以達到所需的效果:

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

然后像

     ## foo

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

foo  ## bar

將通過第二個替代項進行匹配,並且可以從第二個捕獲組中獲取“ ##條”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM