regex - How do I include the operators in my output when I split my string? -


yesterday asked this question splitting string in python. i've since decided project in go instead. have following:

input := "house-width + 3 - y ^ (5 * house length)" s := regexp.mustcompile(" ([+-/*^]) ").split(input, -1) log.println(s)  //  [house-width 3 y (5 house length)] 

how include operators in output? e.g. i'd following output:

['house-width', '+', '3', '-', 'y', '^', '(5', '*', 'house length)'] 

edit: clarify splitting on space-separated operators , not operator. operator must have space on both ends differentiate dash/hyphen. please refer original python question linked clarification if needed.

you can operands of expression using regexp.split() (just did) , can operators (the separators) using regexp.findallstring().

by doing have 2 separate []string slices, can merge these 2 slices if want result in 1 []string slice.

input := "house-width + 3 - y ^ (5 * house length)"  r := regexp.mustcompile(`\s([+\-/*^])\s`)  s1 := r.split(input, -1) s2 := r.findallstring(input, -1)  fmt.printf("%q\n", s1) fmt.printf("%q\n", s2)  := make([]string, len(s1)+len(s2)) := range s1 {     all[i*2] = s1[i]     if < len(s2) {         all[i*2+1] = s2[i]     } } fmt.printf("%q\n", all) 

output (try on go playground):

["house-width" "3" "y" "(5" "house length)"] [" + " " - " " ^ " " * "] ["house-width" " + " "3" " - " "y" " ^ " "(5" " * " "house length)"] 

note:

if want trim spaces operators, can use strings.trimspace() function that:

for i, v := range s2 {     all[i*2+1] = strings.trimspace(v) } fmt.printf("%q\n", all) 

output:

["house-width" "+" "3" "-" "y" "^" "(5" "*" "house length)"] 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -