2014-03-06 31 views
0

我的要求是有通過正則表達式和模式的subregex進行匹配的方法,並退還所有此類subregex如列表等如何基於Java中的另一個正則表達式提取子正則表達式?

如果我通過正則表達式爲^[0-9]{10}-[0-9a-z]{2}.[a-z]{5}$

案例1

method1(regex, patternToMatch) 

我應該得到的值作爲{10}{2}{5}列表。

即,在正則表達式中提取{}中的每個子字符串。

案例2

method1(regex, patternToMatch) 

我應該得到的值作爲[0-9][0-9a-z][a-z]列表。

即,在正則表達式中提取[]中的每個子字符串。

我對Java中的Pattern和Regex不是很熟悉。

請幫我實施這個。

非常感謝幫助!

+0

你可能想用[組](http://docs.oracle.com/javase/7/docs/api/java/u直到/正則表達式/ Pattern.html#CG)。 – Mena

+1

看來你想分解正則表達式到它的標記......請問爲什麼? – fge

+0

@Mena - 請你幫我實施至少1種方法嗎? – user2990685

回答

0

不知道如何做到這一點在Java中,但一般而言,您可以使用像這樣({\d+})/g正則表達式爲獲得在大括號{10}所有的值,{2}和{5}

,同樣你會使用(\[.*?\])/g獲得[0-9],[0-9a-z],[az]。

在線演示在這裏:http://regex101.com/r/mO1kE5

+0

java中的正則表達式不能正常工作。 –

0

這裏是一個程序,將做到這一點:

import java.util.ArrayList; 
import java.util.List; 
import java.util.regex.*; 

/** 
* @author Randy Carlson 
* @version 3/6/14 
*/ 
public class MetaRegex 
{ 
    /** 
    * Main method. 
    * 
    * @param args The command-line arguments. 
    */ 
    public static void main(String[] args) 
    { 
     String regexToMatch = "^[0-9]{10}-[0-9a-z]{2}.[a-z]{5}$"; //the sting you want to find matches in 

     List<String> quantifierNumbers = method1("(?<=\\{).*?(?=})", regexToMatch); //creates an ArrayList containing all the numbers enclosed within {} 
     List<String> charClassContents = method1("(?<=\\[).*?(?=])", regexToMatch); //creates an ArrayList containing all the characters enclosed within [] 

     //The rest of this just prints out the ArrayLists 
     System.out.println("Numbers contained in {}:"); 
     for(String string : quantifierNumbers) 
     { 
      System.out.println(string); 
     } 
     System.out.println(); 
     System.out.println("Contents of []:"); 
     for(String string : charClassContents) 
     { 
      System.out.println(string); 
     } 
    } 

    /** 
    * Gets a list of all of the matches of a given regex in a given string. 
    * 
    * @param regex The regex to match against {@code patternToMatch} 
    * @param patternToMatch The pattern to find matches in. 
    * @return An {@code ArrayList<String>} 
    */ 
    static List<String> method1(String regex, String patternToMatch) 
    { 
     List<String> output = new ArrayList(); //creates an ArrayList to contain the matches 
     Pattern pattern = Pattern.compile(regex); //turns the regex from a string into something that can actually be used 
     Matcher matcher = pattern.matcher(patternToMatch); //creates a Matcher that will find matches in the given string, using the above regex 
     while(matcher.find()) //loops while the matcher can still find matches 
     { 
      output.add(matcher.group()); //adds the match to the ArrayList 
     } 

     return output; //returns the ArrayList of matches 
    } 
} 

輸出:

Numbers contained in {}: 
10 
2 
5 

Contents of []: 
0-9 
0-9a-z 
a-z 
+0

嘿,非常感謝... :)這個工程gr8。 – user2990685