문제

If I have,

String str = "11"; 
Pattern p = Pattern.compile("(\\d)\\1"); 
Matcher m = p.matcher(str); 

How do I store use the result of \1 later? For example I want to do,

String str = "123123"; 
Pattern p = Pattern.compile("(\\d)\\1"); 
Matcher m = p.matcher(str);
String dependantString = //make this whatever was in group 1 of the pattern.

Is that possible?

도움이 되었습니까?

해결책

You need to first call Matcher#find and then Matcher#group(1) like this:

String str = "123123"; 
Pattern p = Pattern.compile("(\\d+)\\1"); 
Matcher m = p.matcher(str);
if (m.find())
    System.out.println( m.group(1) ); // 123

PS: Your regex also needed some correction to use \\d+ instead of \\d.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top