Question

It's tough for me to explain this problem without this example:

I'm looking to replace every instance of the string "switch('Pujols','Albert')" with the string "Albert Pujols", or the string "switch('Cabrera','Melky') with the string "Melky Cabrera", all in Java. What I have thus far is:

line = line.replaceAll("switch\\('(.*)','(.*)'\\)" , "\2 \1");

Which would probably work fine if I could use the \1 and \2 registers to refer to patterns from the first regex (I know I cannot). Is there any way to manipulate this line in Java to my preferences? switch is not a real function I wrote, assume this is all in a text file I'm reading through line by line.

Was it helpful?

Solution

Java uses the $ character for group references:

line = line.replaceAll("switch\\('(.*)','(.*)'\\)" , "$2 $1");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top