问题描述
在 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
但这并不能真正解释谁访问了多个组以及为什么需要使用多维索引。
解决方法
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