用于DSL的正则表达式



我试图写一个正则表达式,捕获两组:第一组是n个单词(其中n>= 0,它是变量),第二组是一组对与此格式field:value。在这两组中,个体之间都用空格隔开。最后,一个可选的空格分隔两组(除非其中一个是空白/nil)。

请考虑以下例子:

'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']

我已经尝试了很多组合和模式,但我不能让它工作。我最接近的模式是/([[w]*s?]*)([w+:[w]+s?]*)/,但它在之前暴露的第二和第三种情况下不能正常工作。

谢谢!

一个正则表达式解:

 (.*?)(?:(?: ?((?: ?w+:w+)+))|$)
  • (.*?)匹配任何东西,但不贪婪,用于查找
  • 则有一组或行尾$
  • 组忽略空格?,然后将所有field:valuew+:w+匹配

查看这里的示例https://regex101.com/r/nZ9wU6/1(我有标志来显示行为,但它最适合单一结果)

不是一个正则表达式,但请尝试一下

string = 'the big apple:something'
first_result = ''
second_result = ''
string.split(' ').each do |value|
  value.include?(':') ? first_string += value : second_string += value
end

最新更新