gpt4 book ai didi

java - 提取字符串、数字组、下一个字符串、下一个数字组

转载 作者:行者123 更新时间:2023-11-30 05:05:21 25 4
gpt4 key购买 nike

我是正则表达式的新手,我正在努力寻找问题的解决方案。我有一个包含多个条目的文件。这是一个例子:

1)你好,我是巴拉巴拉巴拉。等等等等 5677 号楼 - 98 号门等等等等。

2)嗨,我的狗的名字是 blah blah Building 36767 & Door 898900 blah blah blah。

3) 嘿,现在,等等等等 345 DR 898 号楼。等等等等 333 号楼 - 门 89797 等等。

我需要从每一行中提取建筑物号和门号的每个实例。每个条目中唯一不变的模式是:

1)“建筑物”一词始终存在。

2) “Building” 后面总是跟着一组整数...字母“D | d”...以及第二组整数(后跟一个非整数)。

我想要的只是提取建筑物号和门号并打印到控制台,但我无法将其转换为正则表达式模式。我正在使用Java。

最佳答案

我认为这应该有效:

Building.+?(\d+).+?[Dd].+?(\d+)

您的号码将位于第 1 组和第 2 组中。

Building //start by matching "Building"
.+? //then skip over the least number of characters that allows the match
(\d+) //then read as many digits as possible and put them in group one
.+? //then skip over the least number of characters that allows the match
[Dd] //then match an upper- or lower-case 'D'
.+? //then skip over the least number of characters that allows the match
(\d+) //then read as many digits as possible and put them in group two

所以在 Java 中:

Pattern pat = Pattern.compile("Building.+?(\\d+).+?[Dd].+?(\\d+)");
Matcher matcher =
pat.matcher("Hello my is blah blah blah. Blah blah Building 5677 - Door 98 blah blah blah. ");
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}

编辑

要从一个输入中提取多组数字,如第三个示例所示,您可以使用

while (matcher.find()) {

而不是使用 if 只查找一次。

关于java - 提取字符串、数字组、下一个字符串、下一个数字组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5301429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com