如何从解析后的数据中检索位置?
<description>Origin date/time: Mon, 29 Mar 2021 04:23:32 ; Location: BLACKFORD,PERTH/KINROSS ; Lat/long: 56.284,-3.759 ; Depth: 7 km ; Magnitude: 1.0</description>
此详细信息位于描述标记内,并且描述已被解析为数组列表。如何从中获取位置?
最佳答案
您可以使用正则表达式 (?<=Location: ).*?(?= ;)
查找并提取所需的匹配项。
使用 Stream
的解决方案API:
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str = "<description>Origin date/time: Mon, 29 Mar 2021 04:23:32 ; Location: BLACKFORD,PERTH/KINROSS ; Lat/long: 56.284,-3.759 ; Depth: 7 km ; Magnitude: 1.0</description>";
List<String> list = Pattern.compile("(?<=Location: ).*?(?= ;)")
.matcher(str)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
System.out.println(list);
}
}
输出:
[BLACKFORD,PERTH/KINROSS]
非 Stream
解决方案:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "<description>Origin date/time: Mon, 29 Mar 2021 04:23:32 ; Location: BLACKFORD,PERTH/KINROSS ; Lat/long: 56.284,-3.759 ; Depth: 7 km ; Magnitude: 1.0</description>";
Matcher matcher = Pattern.compile("(?<=Location: ).*?(?= ;)").matcher(str);
List<String> list = new ArrayList<>();
while (matcher.find()) {
list.add(matcher.group());
}
System.out.println(list);
}
}
输出:
[BLACKFORD,PERTH/KINROSS]
regex101 处正则表达式的说明:
关于java - RSS FEED - 数据解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66859458/