我正在尝试编写一个捕获两个组的正则表达式:第一个是n个单词组(其中n> = 0且它是变量),第二个是一组具有此格式field:value
的对。在两组中,个体由空格分隔。最终,可选空格将两个组分开(除非其中一个为空/零)。
请考虑以下示例:
'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?]*)/
,但在先前暴露的第二和第三种情况下它无法正常工作。
谢谢!
答案 0 :(得分:1)
不是正则表达式,而是试一试
string = 'the big apple:something'
first_result = ''
second_result = ''
string.split(' ').each do |value|
value.include?(':') ? first_string += value : second_string += value
end
答案 1 :(得分:1)
一个正则表达式解决方案:
(.*?)(?:(?: ?((?: ?\w+:\w+)+))|$)
(.*?)
匹配任何事情,但不贪婪,用于查找单词$
?
,然后将所有field:value
与\w+:\w+
在此处查看示例https://regex101.com/r/nZ9wU6/1(我有标记来显示行为,但它最适合单个结果)