Regex replace to reorder sentences

If I have a line like this:

"word1 'word2' word3"

you can use regex replacement to change the string to this:

"word1 word3 'word2'"

I know what word1 and word3 are, but I don't know what word2 is, but it will always be in single quotes.

+3
source share
4 answers

You can replace "word1 ('\w+') word3"with "word1 word3 \1". Replacement syntax may differ in other regular expression mechanisms; I am using .NET, which is based on Perl.

  • \w+matches a sequence of word characters, aka a word. You can change this if it does not match your definition of the word;
  • . - , - .. ;
  • \1 , \2 ..
+7

:

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

: \"word1 (\'[a-zA-Z0-9]+\') word3\" "word1 word3 \1"

(.+) word2 ( # 1), , - . , \w , - . , , "", .

+3

Following other suggestions ...

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

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

0
source

Source: https://habr.com/ru/post/1764739/


All Articles