Search code examples
regexrubyregex-group

Match long group of characters until multiple consecutive whitespaces ruby regex


I've searched high and low and tried a million combos on rubular and still cannot get this to work. Apologies in advance.

I have the string

ICE - Oct '19 v'19 I                      Bid            Offer        

Any I want to write a regex to group this into chunks of text where a chunk can have any combination of the characters [\w\d-'] and any number of whitespaces as long as they are not consecutive. I want the grouping to terminate as soon as there is more than one white space.

The ouput would be

["ICE - Oct '19 v'19 I", "Bid", "Offer"]

Another option is to say that I want to capture everything, but start a new grouping as soon as there are two consecutive whitespaces.

So the output here would be ["ICE - Oct '19 v'19 I", " Bid", " Offer"]

and then I could stip this Solutions using split are opposed to match will work.

Right now I'm trying something along the lines of ^[\s*\w\-\']+ which doesn't work because I don't know how to specify that everything besides the white space can be + but that whitespace is acceptable but only a single one.

Thanks


Solution

  • Split the string where the split delimiter should be a pattern matching 2 or more whitespaces:

    > "ICE - Oct '19 v'19 I                      Bid            Offer".split(/\s{2,}/)
    => ["ICE - Oct '19 v'19 I", "Bid", "Offer"]