本文介绍了ruby 通过重复字符或空格分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何拆分这个字符串.

How do i split this string.

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

我试过这个,但没有奏效.

I tried this, but it never worked.

ruby-1.8.7-p334 :020 > "111133".split(/(\d)\1+/)
 => ["", "1", "", "3"]

推荐答案

split 将仅使用匹配的任何内容作为分隔符,将其从相关字符串中删除.您正在寻找的是 scan:

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"]

慢慢来,\d 匹配任何数字.它位于第二个捕获组中,因此 \2* 然后匹配相同数字的任何进一步出现.这会产生一个看起来像

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"]]

由于我们只想要每个子数组中的第一项,我们可以使用 map(&:first) 将它们全部收集起来.

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

(注意 str.scan(/(\d)\1*/) 只会从第一个捕获组中生成一个数组,这意味着我们只能从可能重复的数字序列.)

(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.)

这篇关于ruby 通过重复字符或空格分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 07:04