【问题标题】:Groovy null regexGroovy 空正则表达式
【发布时间】:2016-08-11 02:02:32
【问题描述】:

我想做与这个问题相同的任务,但使用 groovy。

REGEX: How to split string with space and double quote

def sourceString = "18 17 16 \"Arc 10 12 11 13\" \"Segment 10 23 33 32 12\" 23 76 21"

def myMatches = sourceString.findAll(/("[^"]+")|\S+/) { match, item -> item }

println myMatches

这是结果

[null, null, null, "Arc 10 12 11 13", "Segment 10 23 33 32 12", null, null, null]

【问题讨论】:

  • 你能提供想要的结果吗
  • 为什么不利用一些可以解析文本并且可以识别字符串分隔符的东西,例如 CSV 解析器?
  • 我会接受@tim_yates 的建议:不要重新发明轮子。

标签: regex groovy


【解决方案1】:

考虑以下,它使用the Elvis operator

def sourceString = '18 17 16 "Arc 10 12 11 13" "Segment 10 23 33 32 12" 23 76 21'

def regex = /"([^"]+)"|\S+/

def myMatches = sourceString.findAll(regex) { match, item -> 
    item ?: match 
}

assert 8 == myMatches.size()

assert 18 == myMatches[0] as int
assert 17 == myMatches[1] as int
assert 16 == myMatches[2] as int
assert "Arc 10 12 11 13" == myMatches[3]
assert "Segment 10 23 33 32 12" == myMatches[4]
assert 23 == myMatches[5] as int
assert 76 == myMatches[6] as int
assert 21 == myMatches[7] as int

【讨论】:

    【解决方案2】:

    返回 match 而不是 item 几乎可以提供预期的结果,但引号仍然存在。不知道如何使用正则表达式排除它们,但从结果中删除引号是可行的:

    def myMatches = sourceString.findAll(/"([^"]+)"|\S+/) { match, item -> match.replace('"', '') }
    

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多