【问题标题】:Regular expression to split by whitespaces that are not inside double/single quotes?正则表达式由不在双/单引号内的空格分割?
【发布时间】:2021-02-22 01:14:39
【问题描述】:

如果我有一个字符串: String string = "Hi my name is "Bob Peters""

只有当字符串没有被引号包围时,我才想用空格分割字符串。而且,我不想在最终结果中包含引号。

所以最终的结果是

Hi, my, name, is, Bob Peters

名字放在一起,其余的分开。

在 groovy 中,这是我目前所拥有的:

def text = "Hi my name is 'Bob Peters'"
def newText = text.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/);
println(newText)

这会导致

Hi
my
name
is
`Bob Peters`

但我也需要能够删除 Bob Peters 周围的单引号/双引号

【问题讨论】:

标签: regex groovy


【解决方案1】:

最简单的选择是有一个额外的步骤来删除引号,如下所示

​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'` 

不会拆分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2010-09-26
    • 2011-05-01
    • 1970-01-01
    • 2013-05-10
    • 2018-02-02
    相关资源
    最近更新 更多