2016-11-06 64 views
1
abc([^\r\n]*) // 0 or more 

abc([^\r\n]+)? // 1 or more, but it's optional 

在Java中。他們看起來和我完全一樣。這兩個正則表達式有什麼區別?

+1

它們對我來說也是一樣。 –

+1

如果使用'abc',第一個會將一個空字符串存儲到第一個捕獲組中,第二個不會存儲這個組,但是我對Java不熟悉,無法知道當您嘗試訪問組時會發生什麼1.請注意,在支持條件匹配(PCRE,Boost,.net等)或替換(Boost)的其他正則表達式中,這可能會產生巨大差異。哦,德爾福在訪問不匹配的命名捕獲羣組時遇到問題。 –

+0

哇。我只是測試它,我想我發佈了錯誤的答案。 https://regex101.com/r/H6nkxD/1表明不同的解析器對於組「'(...)」的行爲確實有區別嗎?''' – Art

回答

2

兩者之間有一個小的差異。下面code

import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

class Example 
{ 
    public static void main (String[] args) 
    { 
     String text = "abc"; 
     Pattern p1 = Pattern.compile("abc([^\\r\\n]*)"); 
     Matcher m1 = p1.matcher(text); 
     if (m1.find()) { 
      System.out.println("MatchCount: " + m1.groupCount()); 
      System.out.println("Group 1: " + m1.group(1)); 
     } else { 
      System.out.println("No match."); 
     } 
     Pattern p2 = Pattern.compile("abc([^\\r\\n]+)?"); 
     Matcher m2 = p2.matcher(text); 
     if (m2.find()) { 
      System.out.println("MatchCount: " + m2.groupCount()); 
      System.out.println("Group 1: " + m2.group(1)); 
     } else { 
      System.out.println("No match."); 
     } 
    } 
} 

給出輸出:

MatchCount: 1 
Group 1: 
MatchCount: 1 
Group 1: null 

所以在字符串abc的情況下,第一正則表達式創建一個捕獲組空的內容,而在第二組是空的,從而不匹配。儘管我對Java並不熟悉,但我猜你必須對待它們有點不同。

旁註:

Java不支持有條件的匹配(不像PCRE,.NET,升壓和多一些)和有條件的更換(不像升壓),其中,這將產生巨大的變化。哦,德爾福有issues with optional named capturing groups