Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace to change the order of words in a sentence

Tags:

regex

If I have a string like this:

"word1 'word2' word3"

is it possible to use a regex replace to change the string to this:

"word1 word3 'word2'"

I know what word1 and word3 will be, but do not know what word2 will be, but it will always be in single quotes.

like image 935
Jeremy Avatar asked Sep 14 '10 18:09

Jeremy


Video Answer


2 Answers

You can replace "word1 ('\w+') word3" with "word1 word3 \1". The replace syntax might be different in other regex engines; I'm using .NET's which is based on Perl's.

  • \w+ matches a series of word characters, aka a word. You can change this if it does not fit your definition of word;
  • The parenthesis are used to delimit groups within the expression. The first is group one, the second is group two, etc. Usually regex engines count group zero as the entire match;
  • The \1 in the replace string means to use group one from the match, \2 means group two, etc.
like image 142
R. Martinho Fernandes Avatar answered Nov 15 '22 13:11

R. Martinho Fernandes


I would say :

s/"(word1)\s+('.+?')\s+(word3)"/"$1 $3 $2"/
like image 20
Toto Avatar answered Nov 15 '22 13:11

Toto