Replace each regex pattern

I am having trouble finding the right template to get the right line.

My starting line is:

,,,,C3:,D3,E3,F3,,

I would like to have

      C3:  [D3,E3,F3]
  • I would like to replace every leading comma with double space
  • Replace coma after colon with double space and left square bracket
  • Replace commas with commas with the right square bracket

At the moment, I have tried this:

> a = ",,,,C3:,D3,E3,F3,,"
=> ",,,,C3:,D3,E3,F3,,"
> b = a.gsub(/^,*/, "  ").gsub(/(?<=:),/, "  [").gsub(/[,]*$/,"" ).gsub(/[ ]*$/, "]")
=> "  C3:  [D3,E3,F3]"
> b == "        C3:  [D3,E3,F3]"
=> false

I cannot achieve to replace each starting comma with double space, in order to get in this case 8 spaces.

Could you help find the correct regular expression and, if possible, improve the code, please?

+4
source share
2 answers

, \G, .. .gsub(/\G,/, ' '). , . , .gsub(/\G,/, ' ').

:

s.gsub(/\G,/, ' ').sub(/,+\z/, ']').sub(/:,+/, ': [')

IDEONE

s = ",,,,C3:,D3,E3,F3,,"
puts s.gsub(/\G,/, '  ').sub(/,+\z/, ']').sub(/:,+/, ':  [')

:

        C3:  [D3,E3,F3]
+6

, :

  • ( , )
  • ,

, :

r = /
    (,*)   # match leading commas in capture group 1
    (.+:)  # match up and including colon in capture group 2
    ,      # match comma     
    (.+)   # match any number of any characters in capture group 3
    ,,     # match two commas
    /x     # extended/free-spacing regex definition mode

",,,,C3:,D3,E3,F3,," =~ r

:

"#{'  '*$1.size}#{$2} [#{$3}]"
  #=> "       C3: [D3,E3,F3]"
0

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


All Articles