user818455 user818455 - 1 month ago 6
Java Question

How to extract data from string value using regex?

Hello I have the following string:

Country number Time Status USA B30111 11:15 ARRIVED PARIS NC0120 14:40 ON TIME DUBAI RA007 14:45 ON TIME


I need to extract following info:

country = USA
number = B30111
time = 11:15
status = ARRIVED

country = PARIS
number = NC0120
time = 14:40
status = ON TIME


How can I use regex to extract the above data from it?

Answer

You can try this:

(?: (\w+) ([\w\d]+) (\d+\:\d+) (ARRIVED|ON TIME))

Explanation

As status can hold more than one word therefore it is not possible to distinct it from the next country that appears, therefore you must append all the possible status as or| in the regex

Java Source:

final String regex = "(?: (\\w+) ([\\w\\d]+) (\\d+\\:\\d+) (ARRIVED|ON TIME))";
final String string = "Country number Time Status USA B30111 11:15 ARRIVED PARIS NC0120 14:40 ON TIME DUBAI RA007 14:45 ON TIME\n\n\n";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
        System.out.println("country =" + matcher.group(1));
        System.out.println("number =" + matcher.group(2));
        System.out.println("time =" + matcher.group(3));
        System.out.println("status =" + matcher.group(4));
        System.out.println("");
}

output

country =USA
number =B30111
time =11:15
status =ARRIVED

country =PARIS
number =NC0120
time =14:40
status =ON TIME

country =DUBAI
number =RA007
time =14:45
status =ON TIME