rubyregexrubular

Regular expression for DSL


I'm trying to write a regular expression that captures two groups: the first is group of n words (where n>= 0 and it's variable) and the second is a group of pairs with this format field:value. In both groups, the individuals are separated by blank spaces. Eventually, an optional space separates the two groups (unless one of them is blank/nil).

Please, take into consideration the following examples:

'the big apple'.match(pattern).captures # => ['the big apple', nil]
'the big apple is red status:drafted1 category:3'.match(pattern).captures # => ['the big apple is red', 'status:drafted1 category:3']
'status:1'.match(pattern).captures # => [nil, 'status:1']

I have tried a lot of combinations and patterns but I can't get it working. My closest pattern is /([[\w]*\s?]*)([\w+:[\w]+\s?]*)/, but it doesn't work properly in the second and third case previously exposed.

Thanks!


Solution

  • The one regex solution:

     (.*?)(?:(?: ?((?: ?\w+:\w+)+))|$)
    

    See an example here https://regex101.com/r/nZ9wU6/1 (I had flags to show the behavior but it works best for single result)