最简单的选择是有一个额外的步骤来删除引号,如下所示
def text = "'Hi there' my name is 'Bob Peters' 'Additional quotes'"
def newText = text.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/);
print(newText.collect {
it.replaceAll(/^['"`](.*)['"`]$/,'$1');
})
它将打印[Hi there, my, name, is, Bob Peters, Additional quotes]
或者,我们可以考虑在space 前面和后面加上引号['"`] 作为拆分模式。
但这不会删除字符串开头和结尾的quotes。我们需要包含备用拆分模式以在字符串的开头和结尾包含引号。
所以模式变成了
^['"`]|['"`]$|['"`]?<<< Your Existing Pattern >>>['"`]?.
这种方法还有另一个问题。如果引号出现在字符串的开头,例如'Hi there ...```,则输出中将添加一个空字符串。
所以我们将在字符串的开头包含一个space,并始终忽略结果数组中的第一个元素。最终模式将是
^\s['"`]|['"`]$|['"`]?<<<Your Existing Pattern>>>['"`]?
Groovy 代码:
def text = "Hi there my name is 'Bob Peters' 'Additional quotes'"
def newText = (" " + text).split(/^\s['"`]|['"`]$|['"`]?\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)['"`]?/);
print(newText[1..newText.size()-1])
将打印[Hi, there, my, name, is, Bob Peters, Additional quotes]
注意: 正向前瞻,\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$) 不会处理 nested quotes。示例
Hi there `Outer quotes 'inner quotes'`
不会拆分。