ruby split string by repeating characters or a space

前端 未结 1 1201
醉酒成梦
醉酒成梦 2020-12-30 05:39

How do i split this string.

\"6885558 8866887777\" => [\"6\", \"88\", \"555\", \"8\", \"88\", \"66\", \"88\", \"7777\"] 

I tried this, b

相关标签:
1条回答
  • 2020-12-30 06:11

    split will just use whatever it matches as a delimiter, removing it from the string in question. What you're looking for is scan:

    str = "6885558 8866887777"
    str.scan(/((\d)\2*)/).map(&:first)
    # => ["6", "88", "555", "8", "88", "66", "88", "7777"]
    

    Taking it slow, the \d matches any digit. It's in the second capturing group, so \2* then matches any further occurrences of the same digit. This produces an array that looks like

    [["6", "6"], ["88", "8"], ["555", "5"], ["8", "8"],
     ["88", "8"], ["66", "6"], ["88", "8"], ["7777", "7"]]
    

    Since we only want the first item in each of those sub arrays, we can collect them all with map(&:first).

    (Note that str.scan(/(\d)\1*/) would simply produce an array out of the first capturing group, which means we'd only get one digit from a sequence of possibly repeated numbers.)

    0 讨论(0)
提交回复
热议问题