Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用正则表达式从字符串值中提取数据?_Java_Regex - Fatal编程技术网

Java 如何使用正则表达式从字符串值中提取数据?

Java 如何使用正则表达式从字符串值中提取数据?,java,regex,Java,Regex,您好,我有以下字符串: 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 TIM

您好,我有以下字符串:

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

如何使用正则表达式从中提取上述数据?

如果您基于拆分函数创建一个数组,那么该数组中将包含每个单词

String[] splitted = str.split(" ");
然后,要检查,请尝试以下操作:-

for(String test:splitted){
    System.out.println(test);
}
这看起来更像一个CSV文件。

您可以尝试以下方法:

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

由于status可以包含多个单词,因此无法将其与出现的下一个国家/地区区分开来,因此必须在regex中附加所有可能的status As或|

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

首先,您可以通过空格分割来提取第一个文件,或者您需要使用正则表达式吗?这看起来更像是CSV类型的文件,您应该使用现有的解析器。鉴于您的代表为4位数字,此问题显示没有任何研究工作。你应该知道这不是一个代码编写服务。哇..我几乎认为这是不可能的,那么容易。但是该死的。你做到了…太好了。。!!