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"
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 wordEdit
or like Wiktor Stribiżew mention you can use \\b(\\w+)\\s+(\\w+)\\b
instead, this work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With