Donal Rafferty
Donal Rafferty

Reputation: 19826

word space word regex in Ruby?

I am trying to split a String in Ruby based on a regex.

The String has the following pattern:

00 0 0 00 00 0

I want to be able to split the string on every second space but I am quite new to Ruby and my experience with Regexes is limited.

I have tried the following:

line.split(/[0-9._%+-]+\s+[0-9._%+-]+/)

But this just returns an array of blank values. I have tried various different combinations of the regex pattern but have not got close to what I want. The result should be an array like this:

Array[0] => '00 0'
Array[1] => '0 00'
Array[2] => '00 0'

Could anyone explain how I could best do this in a Regex? And if possible explain why my attempt doesn't work and why you're working example does work, I want to increase my knowledge of Regexes by solving this problem.

Upvotes: 0

Views: 61

Answers (2)

Pedram
Pedram

Reputation: 234

When using RegEx to split a given string, the matched part is removed from the result set. Therefore you cannot use the RegEx syntax to split those numbers and keep the values at the same time.

Use the following code instead:

"00 0 0 00 00 0".scan(/[0-9]+\s[0-9]+/)

Upvotes: 1

Adrian
Adrian

Reputation: 15171

Use String#scan

line = "00 0 0 00 00 0"
line.scan(/[0-9._%+-]+\s+[0-9._%+-]+/)
#=> ["00 0", "0 00", "00 0"]

When you use String#split, you pass a regex to match the things that you don't want in your output. That is, the things that should be in between the strings in the output array.

Upvotes: 2

Related Questions