groovy - 在groovy(匹配器组)中访问多行字符串中的多个匹配项
问题描述
在 groovy 中,我有这个多行字符串,我试图使用匹配器和正则表达式模式来使用 [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)
所以我可以访问的第一个号码 2234[0][1]
但是我如何访问下一个号码?
更一般地说,对匹配器的多维数组访问如何工作+记录?
我发现:
https://blog.mrhaki.com/2009/09/groovy-goodness-matchers-for-regular.html
和:
但这并不能真正解释谁访问了多个组以及为什么需要使用多维索引。
解决方案
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
推荐阅读
- python - 使用 Sphinx 记录 Django 项目
- javascript - 在 ReactJs 中自动上下滚动表格
- mongodb - Java - 使用 MongoDB 集合 bulkWrite 插入/更新
- terraform - Terraform 模块来源:目标最新版本和 GitHub 中的特定文件
- python - 如何使用功能供计算机选择
- r - 如何使用 ggplot2 将 Latitude_min、Latitude_max、Longitude_min 和 Longitude_max 绘制为网格/四边形形式?
- r - 来自不同包的两个功能不能一起工作
- file-upload - 雪花 - Azure 文件上传 - 如果文件大小超过 40MB,我如何对文件进行分区
- python - 在 Python 中做一个双 sshtunnel 服务器跳转
- php - diglactic/laravel-breadcrumbs 有没有其他方法可以编写面包屑而不是将其全部写入面包屑文件?