Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested regexps and replace

Tags:

java

regex

I have strings like this <p0=v0 p1=v1 p2=v2 ....> and I want to swap pX with vX to have something like <v0=p0 v1=p1 v2=p2 ....> using regexps. I want only pairs in <> to be swapped.

I wrote:

Pattern pattern = Pattern.compile("<(\\w*)=(\\w*)>");
Matcher matcher = pattern.matcher("<p1=v1>");
System.out.println(matcher.replaceAll("$2=$1"));

But it works only with a single pair pX=vX Could someone explain me how to write regexp that works for multiple pairs?


1 Answers

Simple, use groups:

String input = "<p0=v0 p1=v1 p2=v2>";
//                                   |group 1
//                                   ||matches "p" followed by one digit
//                                   ||      |... followed by "="
//                                   ||      ||group 2
//                                   ||      |||... followed by "v", followed by one digit
//                                   ||      |||          |replaces group 2 with group 1,
//                                   ||      |||          |re-writes "=" in the middle
System.out.println(input.replaceAll("(p[0-9])=(v[0-9])", "$2=$1"));

Output:

<v0=p0 v1=p1 v2=p2>
like image 88
Mena Avatar answered Feb 06 '26 21:02

Mena