R regex - match the first combination of space letters from the end

I have the following row vector:

x = c("Breakfast Sandwich 12.6 - 18.4oz 4 - 8ct", 
      "Buffalo Wing 7.6 - 10 oz", 
      "Asstd Cafe Appetizer 8 - 20", 
      "16in Extra Lrg Pepperoni 45.5oz") 

I need to move the size to the beginning of the line, but I cannot create the correct regexcall for it. If more than one combination is found, move only the last combination. The moved part will always be preceded by a letter and a space. The desired result will be:

"4 - 8ct Breakfast Sandwich 12.6 - 18.4oz", 
"7.6 - 10 oz Buffalo Wing", 
"8 - 20 Asstd Cafe Appetizer", 
"45.5oz 16in Extra Lrg Pepperoni"

I think a non-greedy match until something like that is found [a-z] [0-9].*?? Or can it be used instead split? Could you help me? Thank you in advance!

Btw, if for all test cases there is no one-step solution, a series of individual ones gsubwill work.

+4
3

, -, :

sub("(.*[a-z]{1}) ([0-9.]+\\s*-?\\s*[0-9.]*\\s*[a-z]*\\s*)$", "\\2 \\1", x)

+3

:

 gsub('(.*(?<=\\w)) (\\d.*$)','\\2 \\1',x,perl=T)
[1] "4 - 8ct Breakfast Sandwich 12.6 - 18.4oz" "7.6 - 10 oz Buffalo Wing"                 "8 - 20 Asstd Cafe Appetizer"             
[4] "45.5oz 16in Extra Lrg Pepperoni"  
+3

.

sub("(.*[a-zA-Z]) +(\\d.*)", "\\2 \\1", x)
# [1] "4 - 8ct Breakfast Sandwich 12.6 - 18.4oz" "7.6 - 10 oz Buffalo Wing"                
# [3] "8 - 20 Asstd Cafe Appetizer"              "45.5oz 16in Extra Lrg Pepperoni" 
+2
source

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


All Articles