Regex replace to change the order of words in a sentence

前端 未结 4 1578
遇见更好的自我
遇见更好的自我 2020-12-17 03:20

If I have a string like this:

\"word1 \'word2\' word3\"

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

相关标签:
4条回答
  • 2020-12-17 03:41

    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.

    0 讨论(0)
  • 2020-12-17 03:44

    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.
    0 讨论(0)
  • 2020-12-17 03:52

    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+([^"]+?(?>"))$

    0 讨论(0)
  • 2020-12-17 03:57

    I would say :

    s/"(word1)\s+('.+?')\s+(word3)"/"$1 $3 $2"/
    
    0 讨论(0)
提交回复
热议问题