Looking to replace a pattern of one string with a string that uses info from the pattern found?

StackOverflow https://stackoverflow.com/questions/21134323

  •  28-09-2022
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

Java uses the $ character for group references:

line = line.replaceAll("switch\\('(.*)','(.*)'\\)" , "$2 $1");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top