有分析这段文字到地图的简单方法 [英] Is there a simple way of parsing this text into a Map

查看:95
本文介绍了有分析这段文字到地图的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到如下一个服务的响应。如何解析成地图吗?我首先想到的拆分在空格,但它不工作的值可能包含空格例如:看的值 SA 键在下面的响应。

I receive the response from a service as below. How to parse this into a Map? I first thought of split at whitespace but it doesn't work as the value might contain spaces e.g. look at the value of SA key in the below response.

一个选择,我认为是分裂的空白提供的previous字符是双引号。不知道怎么写的正则表达式这虽然。

One option I thought of is to split at whitespace provided the previous character is a double quote. Not sure how to write the regex for this though.

TX =0000000000108000001830001FI =OS =8CI =QU01SF1S2032AW =SSSSA =1525迎风广场

TX="0000000000108000001830001" FI="" OS="8" CI="QU01SF1S2032" AW="SSS" SA="1525 Windward Concourse"

推荐答案

解析的报价。你甚至可以使用常规的EX pression找到每个键/值对,假设每个值都在引号。我唯一​​的问题是,什么是对,如果值中包含嵌入引号的规则? (他们是否躲过使用'\'或者这样?无论如何,这不是目前占在下面的...)

Parse at quotes. You could even use a regular expression to find each key/value pair, assuming each value is in quotes. My only question would be, what are the rules for if a value contains embedded quotes? (Are they escaped using '\' or such? Regardless, this is not currently accounted for in the below...)

例如:

(\w+)="([^"]*)"

这将甚至给你组#1和#2,其可以被用来提供分别的键和值,

This will even give you groups #1 and #2 that can be used to provide the key and the value, respectively.

运行这个在一个循环中,使用Java的 Matcher.find()方法,直到找到所有的对。

Run this in a loop, using Java's Matcher.find() method, until you find all of the pairs.

样品code:

String input = "TX=\"0000000000108000001830001\" FI=\"\" OS=\"8\" CI=\"QU01SF1S2032\" AW=\"SSS\" SA=\"1525 Windward Concourse\"";

Pattern p = Pattern.compile("\\s*(\\w+)=\"([^\"]*)\"\\s*");

Matcher m = p.matcher(input);
while(m.find()){
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}

输出:

TX
0000000000108000001830001
FI

OS
8
CI
QU01SF1S2032
AW
SSS
SA
1525 Windward Concourse

这篇关于有分析这段文字到地图的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆