Groovy字符串拆分正则表达式无法正常工作 [英] Groovy string split regular expression is not working properly

查看:75
本文介绍了Groovy字符串拆分正则表达式无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Groovy的 split()方法,并且我有以下代码

I'm using Groovy split() method and I have the following code

def value = '-t "not @healthcheck"'

println(value.split(/[^\s"']+|"([^"]*)"|'([^']*)'/))

我从基本上,我想按空格分隔字符串,但如果用单引号/双引号引起来则不要.

Basically I want to split my string by whitespace but not if it's surrounded by single/double quotes.

我想要的最终结果是 [-t,而不是@healthcheck] ,但是我得到的是 [,,] .我不明白为什么所有值都为空.也许我的正则表达式不正确,或者我不理解常规语法弄乱了某些东西.

My end result I want is [-t, not @healthcheck] but I'm getting [, , ]. I don't understand why all the values are empty. Maybe my regular expression isn't correct or I don't understand groovy syntax messing up something.

推荐答案

我认为您不应在此处使用 split().我宁愿这样使用模式匹配:

I think you should not use split() here. I'd rather use pattern matching like so:

def value = '-t "not @healthcheck"    -t "111" -v "222" -c ahska@jhd'

def list = ( value =~ /(-[a-z]+)\s+"?([^"-]+)"?/ ).collect{ _, key, val -> [ key, val ] }

println list.join( '\n' )

打印:

[-t, not @healthcheck]
[-t, 111]
[-v, 222]
[-c, ahska@jhd]

这篇关于Groovy字符串拆分正则表达式无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆