This is my data and its pattern:
// _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+";
Underscores are space character. Now I need a class that divides every regex term to data. For example
\\s+ = " "
\\d{2} = "23"
. = "."
\\d{2} = "02"
\\s = " "
[A-Z]+ = "ANTALYA"
etc... That must be ordered by pattern.
How can I do this or is there a library for this?
As @devnull mentioned, you should use 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+)
See the full explanation of this regular expression on Regex101 .
You would then use something like the following to match the text and extract the individual values:
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));
}
}
To make it easier to extract specific fields, you could (in Java 7 and later) use named capturing groups:
(?<LeadSpace>\s+)(?<Day>\d{2})(.)(?<Month>\d{2})...
You could then use something like the following to get each named group:
...
if (matcher.find()) {
System.out.println(matcher.group("LeadSpace"));
System.out.println(matcher.group("Day"));
System.out.println(matcher.group("Month"));
...
}
I found a different way. I divided pieces with my hand.
// _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+" );
After this I used a loop and everything is fine. This question can close.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.