DSL 的正则表达式

Regular expression for DSL

我正在尝试编写一个捕获两组的正则表达式:第一个是 n 个单词组(其中 n>= 0 并且它是可变的),第二个是一组具有这种格式的对 field:value.在这两个组中,个体被空白 space 分隔开。最终,一个可选的 space 将两组分开(除非其中一个是 blank/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?]*)/,但在之前曝光的第二种和第三种情况下它不能正常工作

谢谢!

不是正则表达式,但试一试

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

string.split(' ').each do |value|
  value.include?(':') ? first_string += value : second_string += value
end

一个正则表达式解决方案:

 (.*?)(?:(?: ?((?: ?\w+:\w+)+))|$)
  • (.*?) 匹配任何东西但不贪心,用于查找单词
  • 然后有一组或行尾$
  • 小组忽略 space ? 然后将所有 field:value\w+:\w+
  • 匹配

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