[英]How do I extract a sub-regex expression based on another regex value in Java?
我的要求是要有一個傳遞正則表達式和要與子正則表達式匹配的模式並返回所有此類子正則表達式的方法,例如list等。
如果我將正則表達式作為^[0-9]{10}-[0-9a-z]{2}.[az]{5}$
傳遞^[0-9]{10}-[0-9a-z]{2}.[az]{5}$
情況1
method1(regex, patternToMatch)
我應該在列表中得到{10}
, {2}
和{5}
的值。
即,提取正則表達式中{}內的每個子字符串。
案例2
method1(regex, patternToMatch)
我應該在列表中得到[0-9]
, [0-9a-z]
和[az]
。
即,提取正則表達式[]中的每個子字符串。
我對Java中的Pattern和Regex不太熟悉。
請幫助我實現這一點。
感謝大量的幫助!
不確定如何在Java中執行此操作,但是通常您會使用({\\d+})/g
這樣的正則表達式來獲取花括號{10},{2}和{5}中的所有值
同樣,您將使用(\\[.*?\\])/g
獲得[0-9],[0-9a-z],[az]。
此處的在線演示: http : //regex101.com/r/mO1kE5
這是一個可以做到的程序:
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 az
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.