如何在GROUP BY和第一个空格之间匹配字符串而不使用逗号?

时间:2017-01-28 13:22:24

标签: regex

有字符串:

GROUP BY id,asd, asddd, adfasd LIMIT 4;
=> id,asd, asddd, adfasd

GROUP BY id,asd, asddd, adfasd order id asc;
=> id,asd, asddd, adfasd

GROUP BY id limit 4;
=> id

如何匹配 GROUP BY 与没有逗号的第一个空格之间的值??

2 个答案:

答案 0 :(得分:4)

试试这个正则表达式:

GROUP BY (.*[^\s]+\s*,\s*[^\s]+)

在这里演示:

Regex101

答案 1 :(得分:1)

这个正则表达式完成了这项工作:(?<=GROUP BY\s+)(\w+(?:\s*,\s*\w+)*)

<强>解释

(?<=GROUP BY\s+): lookbehind, make sure we have "GROUP BY"
(               : start group 1    
  \w+           : 1 or more word character
  (?:           : start non capture group
    \s*         : 0 or more spaces
    ,           : a comma
    \s*         : 0 or more spaces
    \w+         : 1 or more word character
  )*            : group may occurs 0 or more times
)               : end group 1

输入字符串:

GROUP BY id,asd, asddd, adfasd LIMIT 4;
GROUP BY id,asd, asddd, adfasd order id asc;
GROUP BY id , asd limit 4;

输出:

'id,asd, asddd, adfasd'
'id,asd, asddd, adfasd'
'id , asd'