解决方法
将正则表达式更改为abc(.*)def(.*)pqr(.*)xyz,括号将自动绑定到
>变量$1到$3 if
你使用String.replaceAll()或
> Matcher.group(n)如果您使用
Matcher.find()
有关详细信息,请参阅Pattern class的文档,尤其是Groups and Capturing.
示例代码:
final String needle = "abc(.*)def(.*)pqr(.*)xyz"; final String hayStack = "abcXdefYpqrZxyz"; // Use $variables in String.replaceAll() System.out.println(hayStack.replaceAll(needle,"_$1_$2_$3_")); // Output: _X_Y_Z_ // Use Matcher groups: final Matcher matcher = Pattern.compile(needle).matcher(hayStack); while(matcher.find()){ System.out.println( "A: " + matcher.group(1) + ",B: " + matcher.group(2) + ",C: " + matcher.group(3) ); } // Output: A: X,B: Y,C: Z