您好我有以下字符串:
Country number Time Status USA B30111 11:15 ARRIVED PARIS NC0120 14:40 ON TIME DUBAI RA007 14:45 ON TIME
我需要提取以下信息:
country = USA
number = B30111
time = 11:15
status = ARRIVED
country = PARIS
number = NC0120
time = 14:40
status = ON TIME
如何使用正则表达式从中提取上述数据?
答案 0 :(得分:1)
你可以试试这个:
(?: (\w+) ([\w\d]+) (\d+\:\d+) (ARRIVED|ON TIME))
由于状态可以包含多个单词,因此无法将其与出现的下一个国家区分开来,因此您必须将所有可能的状态添加为或在正则表达式
Java来源:
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("");
}
<强>输出强>
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
答案 1 :(得分:0)
如果您基于分割功能创建一个数组,那么您将拥有该数组中的每个单词。
String[] splitted = str.split(" ");
然后检查,试试这个: -
for(String test:splitted){
System.out.println(test);
}
这看起来更像是一个CSV文件。