Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for swapping words

Tags:

java

regex

I'm a regular expression newbie, and I am unable to figure out how to write a single regular expression that would swap pairs of consecutive words. For example, if the sentence is "How are you today guys" then the result should be "are How today you guys"

like image 681
Misho Tek Avatar asked Oct 14 '25 15:10

Misho Tek


1 Answers

You can try to use regex groups, so your regex can be (\b\w+\b)\s+(\b\w+\b) so with replaceAll it can be :

String str = "How are you today guys";
String regex = "(\\b\\w+\\b)\\s+(\\b\\w+\\b)";
System.out.println(str.replaceAll(regex, "$2 $1"));

Outputs

are How today you guys

meaning :

  • (\b\w+\b) capture first word
  • \s+ which is followed by a space or more
  • (\b\w+\b) capture second word

Edit

or like Wiktor Stribiżew mention you can use \\b(\\w+)\\s+(\\w+)\\b instead, this work fine.

like image 85
YCF_L Avatar answered Oct 17 '25 03:10

YCF_L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!