0

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!

tehAnswer
  • 960
  • 1
  • 13
  • 28

2 Answers2

1

Not a regexp, but give it a try

string = 'the big apple:something'
first_result = ''
second_result = ''

string.split(' ').each do |value|
  value.include?(':') ? first_string += value : second_string += value
end
Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
  • Thanks! But I'm trying to solve it with regexp. Anyways, I've voted positive because you proposed a _valid but alternative_ solution! – tehAnswer Oct 06 '15 at 13:45
1

The one regex solution:

 (.*?)(?:(?: ?((?: ?\w+:\w+)+))|$)
  • (.*?) match anythings but is not greedy and is used to find words
  • then there is a group or the end of line $
  • the group ignore the space ? then match all field:value with \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)

Cyrbil
  • 6,341
  • 1
  • 24
  • 40
  • You're my man! It worked perfectly. Can you explain little more what `?:` does and how the solution behaves? It seems magic to me : D – tehAnswer Oct 06 '15 at 13:51
  • it was a hard one but fun to do :D had to redo it 4 times to match perfectly all cases – Cyrbil Oct 06 '15 at 13:53