Question
Is there a way in Java to refer to previous matched groups within the regex?
How-To
Sample code as below:
- package howto;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Test {
- public static void main(String[] args) throws Exception
- {
- String str = "A123 A123 A123 A123";
- // The outermost () is group1; So "(\\w\\d\\d\\d)" is group2.
- Pattern ptn = Pattern.compile("((\\w\\d\\d\\d)(\\s+\\2)*)");
- Matcher mth = ptn.matcher(str);
- if(mth.find())
- {
- for(int i=0; i
- {
- System.out.printf("G%d: '%s'\n", i+1, mth.group(i+1));
- }
- }
- else
- {
- System.err.printf("Miss!\n");
- }
- }
- }
沒有留言:
張貼留言