这是我的数据及其模式:
// _23.02_ANTALYA____________FRANKFURT___________DE_7461_18:20-21:00________________
public static final String FLIGHT_DEFAULT_PATTERN = "\\s+\\d{2}.\\d{2}\\s[A-Z]+\\s+[A-Z]+\\s+[A-Z\\s]{3}[\\d\\s]{5}\\d{2}:\\d{2}-\\d{2}:\\d{2}\\s+";
下划线是空间角色。现在我需要一个将每个正则表达式术语划分为数据的类。例如
\\s+ = " "
\\d{2} = "23"
. = "."
\\d{2} = "02"
\\s = " "
[A-Z]+ = "ANTALYA"
等......必须按模式排序。
我该怎么办?或者是否有图书馆?
答案 0 :(得分:2)
正如@devnull所提到的,你应该使用capturing groups:
(\s+)(\d{2})(.)(\d{2})(\s)([A-Z]+)(\s+)([A-Z]+)(\s+)([A-Z\s]{3})([\d\s]{5})(\d{2}:\d{2})(-)(\d{2}:\d{2})(\s+)
在Regex101上查看此正则表达式的完整说明。
然后,您将使用以下内容匹配文本并提取单个值:
String text = " 23.02 ANTALYA FRANKFURT DE 7461 18:20-21:00 ";
Pattern pattern = Pattern.compile("(\\s+)(\\d{2})(.)(\\d{2})(\\s)([A-Z]+)(\\s+)([A-Z]+)(\\s+)([A-Z\\s]{3})([\\d\\s]{5})(\\d{2}:\\d{2})(-)(\\d{2}:\\d{2})(\\s+)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
for (int i = 1; i < matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
为了更容易提取特定字段,您可以(在Java 7及更高版本中)使用命名捕获组:
(?<LeadSpace>\s+)(?<Day>\d{2})(.)(?<Month>\d{2})...
然后您可以使用以下内容来获取每个命名组:
...
if (matcher.find()) {
System.out.println(matcher.group("LeadSpace"));
System.out.println(matcher.group("Day"));
System.out.println(matcher.group("Month"));
...
}
答案 1 :(得分:0)
我发现了一种不同的方式。我用手分开了碎片。
// _24.02_MAURITIUS_________HAMBURG________________via:FRA_DE/LH____08:30-20:05_____
public static final List<String> FLIGHT_VIA_PATTERN = Arrays.asList( "\\s+", "\\d{2}", "\\.", "\\d{2}", "\\s+", "[A-Z]+", "\\s+", "[A-Z]+", "\\s+", "via:", "[A-Z\\s]{4}", "[A-Z]{2,3}", "/",
"[A-Z]{2,3}", "\\s+", "\\d{2}", ":", "\\d{2}", "\\-", "\\d{2}", ":", "\\d{2}", "\\s+" );
在此之后我使用了一个循环,一切都很好。这个问题可以结束。