deeb
deeb

Reputation: 1382

Ruby regex for a split every four characters not working

I'm trying to split a sizeable string every four characters. This is how I'm trying to do it:

big_string.split(/..../)

This is yielding a nil array. As far as I can see, this should be working. It even does when I plug it into an online ruby regex test.

Upvotes: 26

Views: 17027

Answers (3)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Hmm, I don't know what Rubular is doing there and why - but

big_string.split(/..../)

does translate into

split the string at every 4-character-sequence

which should correctly result into something like

["", "", "", "abc"]

Upvotes: 1

CodeJoust
CodeJoust

Reputation: 3800

Whoops.

str = 'asdfasdfasdf'
c = 0
out = []
inum = 4
(str.length / inum).round.times do |s|
    out.push(str[c, round(s * inum)])
    c += inum
end

Upvotes: 0

Ryan McGeary
Ryan McGeary

Reputation: 240044

Try scan instead:

$ irb
>> "abcd1234beefcake".scan(/..../)
=> ["abcd", "1234", "beef", "cake"]

or

>> "abcd1234beefcake".scan(/.{4}/)
=> ["abcd", "1234", "beef", "cake"]

If the number of characters isn't divisible by 4, you can also grab the remaining characters:

>> "abcd1234beefcakexyz".scan(/.{1,4}/)
=> ["abcd", "1234", "beef", "cake", "xyz"]

(The {1,4} will greedily grab between 1 and 4 characters)

Upvotes: 89

Related Questions