【发布时间】: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
但这并不能真正解释谁可以访问多个组以及为什么需要使用多维索引。
【问题讨论】: