2013-04-05 124 views
-1

我有一個要求,我想在兩個不同的項目形成一個長字符串。 我已經得到了下面的程序,當我做組(1)和組(6)時,我獲得了必需的項目。 但我想在組(1)和組(2)中得到它。正則表達式與兩個模式

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

public class RegexExample { 
public static void main(String args[]) { 
    String somepattern = "((123|456)-(0|1)-((\\d-?){8})-\\d{1})/(\\d{2})"; 


    String str = "/somethingwaste/123-0-1234-5678-9/10"; 
    Matcher p = Pattern.compile(somepattern).matcher(str); 
    while (p.find()) { 
    System.out.println(p.group(1)); 
    System.out.println(p.group(6)); 
    } 

任何指針方向appriciated。

感謝

+2

魔術字是'非捕獲組'。請在正則表達式文檔中查找它。 – Ingo 2013-04-05 12:19:30

+0

如果你有問題,並決定用正則表達式解決它,那麼你有兩個問題=) – svz 2013-04-05 12:26:12

回答

2

只是要組你不想繼續使用non-capturing?:

String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})"; 
String str = "/somethingwaste/123-0-1234-5678-9/10"; 
Matcher p = Pattern.compile(somepattern).matcher(str); 
while (p.find()) { 
    System.out.println(p.group(1)); 
    System.out.println(p.group(2)); 
} 
3

這應該這樣做

String somepattern = "((?:123|456)-[01]-(?:\\d-?){8}-\\d)/(\\d{2})"; 

?:使得()非捕獲。

+0

在我看來這是一個更好的答案,因爲它消除了模式中的冗餘。 – nhahtdh 2013-04-05 13:21:33