tags:

views:

65

answers:

4

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.

+2  A: 

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.
Martinho Fernandes
The question states "I know what word1 and word3 will be", hence no need for `(\w+)`.
z5h
@z5h: yeah, you're right, I didn't notice. I'll make it more specific.
Martinho Fernandes
It's ok, I derived what I needed from the answer. Thanks!
Jeremy
+2  A: 

Search for: \"word1 (\'[a-zA-Z0-9]+\') word3\" And replace with "word1 word3 \1"

You could also use (.+) for word2 (in capture group #1), if you want to match more than just alphanumeric characters. I think \w could also be used, but for some reason I don't use that very often. Maybe I don't always agree with the regex engine about what should be a "word" character, so I prefer to be more explicit.

FrustratedWithFormsDesigner
A: 

Following the other suggestions...

this expression will make sure that word3 is the final word in the string (forward look for " and then end-of-string), but allows for any characters for your 'words' except single and double quotes.

('[^']+?')\s+([^"]+?(?>"))$

Brad
+3  A: 

I would say :

s/"(word1)\s+('.+?')\s+(word3)"/"$1 $3 $2"/
M42