【问题标题】:Accessing multiple matches in a multiline string in groovy (matcher groups)在groovy(匹配器组)中访问多行字符串中的多个匹配项
【发布时间】:2021-03-25 18:00:42
【问题描述】:

在 groovy 中,我有这个多行字符串,我试图使用 matcher 和正则表达式 pattern 来使用 [x][y] 提取数字符号:

String input = """\
2234 This is a sample text
1424 This second 2335 line
This id third 455 line
Welcome to Tutorialspoint
        """.stripIndent()

println ((input =~ "^([0-9]+).*")[0][1])
println ((input =~ "^([0-9]+).*")[1][1])

当我运行上述内容时,我得到:

2234

java.lang.IndexOutOfBoundsException: index is out of range -1..0 (index = 1)

所以我可以使用[0][1] 访问第一个号码 2234,但是如何访问下一个号码?

更一般地说,对匹配器的多维数组访问是如何工作的?

我找到了:

https://blog.mrhaki.com/2009/09/groovy-goodness-matchers-for-regular.html

和:

Groovy syntax for regular expression matching

但这并不能真正解释谁可以访问多个组以及为什么需要使用多维索引。

【问题讨论】:

    标签: groovy matcher


    【解决方案1】:
    String input = """\
        2234 This is a sample text
        1424 This second 2335 line
        This id third 455 line
        Welcome to Tutorialspoint
        """.stripIndent()
        
    input.findAll(/[0-9]+/)
    

    如果您只希望每行开头的数字:

    input.findAll(/(?m)^[0-9]+/)
    

    在你的情况下,正则表达式匹配整个字符串。

    您可以指定多行标志(?m) 来逐行处理输入

    println ((input =~ "(?m)^([0-9]+).*")[0][1])
    println ((input =~ /(?m)^([0-9]+).*/)[1][1])
    

    https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#MULTILINE

    【讨论】:

    • 好吧,我的意思是更多地理解/如何使用 [x][y] 符号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    相关资源
    最近更新 更多