user7055375
user7055375

Reputation:

Having trouble splitting on a regular expression and putting the results into an array

I'm using Ruby 2.4. I'm having trouble splitting on a regular expression and getting the results into an array. If I have a string like

"A other stuff"

I want to split the first character from teh rest of the string, only if the first character is an "A" or a "B" and there is a space after it. So by those rules, splitting the above would result in

["A", "other stuff"]

but applying those rules to

"Aother stuff"

would result in

["Aother stuff"]

(because there is no space after the "A"). I tried

2.4.0 :007 > str = "A more"
 => "A more" 
2.4.0 :009 > str.split(/^([ab])[[:space:]]+/i)
 => ["", "A", "more"]

but there is this annoying blank character at the beginning of my array, whcih I dont' want there. Thanks for the advice.

Upvotes: 2

Views: 51

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

Here's a method that does not employ a regular expression.

def doit(str)
  (!str.empty? && "ABab".include?(str[0]) && str[1] == ' ') ?
    [str[0], str[2..-1].lstrip] : [str]
end

doit 'A lot of stuff'     #=> ["A", "lot of stuff"] 
doit 'B     lot of stuff' #=> ["B", "lot of stuff"] 
doit 'C lot of stuff'     #=> ["C lot of stuff"] 
doit 'Alot of stuff'      #=> ["Alot of stuff"] 
doit 'B '                 #=> ["B", ""] 
doit 'b'                  #=> ["b"] 
doit ''                   #=> [""] 

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

Use a lookbehind assertion (that means preceded by):

yourstring.split(/(?<=^[ab])\s+/i)

The main interest of lookaround assertions is that they are only tests, they don't consume characters and are not returned in the match result.

Note that since you only need to split your string once, may be if you set the second parameter of the split method to 2, it will stop the search at the first occurrence (need to be confirmed):

 yourstring.split(/(?<=^[ab])\s+/i, 2)

Upvotes: 1

Related Questions