2016-04-02 34 views
1

我需要從下面的字符串獲得每個塊Foo。我用這個正則表達式。代碼如下。但由於正則表達式的部分($|( ..F))我只得到Foo[1]Foo[3]。我怎樣才能得到每個Foo塊與正則表達式?Groovy正則表達式匹配不包含

import java.util.regex.Matcher 

String test = ''' ..Foo[1]dsfsdf 
    ...........sfsdfdsfsdfsdf 
    ..............sdfffffffffsd 
    ..................sdffffffffffffffff 
    ..Foo[2]dsfsdf 
    ...........sfsdfdsfsdfsdf 
    ..............sdfffffffffsd 
    ..................sdffffffffffffffff 
    ..Foo[3]dsfsdf 
    ...........sfsdfdsfsdfsdf 
    ..............sdfffffffffsd 
    ..................sdffffffffffffffff 
    ..Foo[4]dsfsdf 
    ...........sfsdfdsfsdfsdf 
    ..............sdfffffffffsd 
    ..................sdffffffffffffffff''' 

Matcher m = test =~ /(Foo\[[0-9]{1,6}\][\s\S]*?)($|( ..F))/ 
m.find(); 
//after this m.count equals 2 and contains only Foo[1] and Foo[3], but I need 4 with all Foo's 
+0

這不是我明白 –

+0

@YassinHajaj爲什麼? Groovy語法? Java等效:Pattern p = Pattern.compile(「(Foo \ [[0-9] {1,6} \] [\ s \ S] *?)($ |(..F))」); Matcher m = p.matcher(test); m.find() –

+0

好吧,我沒有注意到這是groovy。抱歉。 –

回答

0

你只需要通過開(後加入?=使將其變成一個positive lookahead($|( ..F))非消費(和逃生點,使他們能夠匹配文本點):

(Foo\[[0-9]{1,6}\][\s\S]*?)(?=$| \.\.F) 
          ^^^^^^^^^^^^^ 

查看regex demo

+0

請參閱[IDEONE演示](http://ideone.com/4K6lvN)將'm.count'結果打印爲'4' –

+0

非常感謝 –

+0

請注意,延遲匹配不是匹配非常長的塊的最佳方式([Foo \ [[0-9] {1,6} \] [^] *(?:(?!\。\。F)[^] *)*)' ](https://regex101.com/r/sF0kY4/2)。比較綠色框中所需的步驟數量。 222與1787.'[^]'可以用'\ S'替代,而用'\ s'替代空格。 –

相關問題