java字符串转义字符,使用Java解析包含转义字符的字符串

I wonder if someone could help me figure out how to parse a string having the following format:

;field1-field2-fieldN;field1-field2-fieldN;

Each record is delimited by ';' and each field within a record is delimited by '-'. The complication is that the individual fields may contain escaped delimiter characters like so "\;" or "-". This causes my simple parsing code below to fail. So what I'm trying to do is come up with regex expressions that will match the delimiters but not match the escaped delimiters.

My regex knowledge is not that great but I expected there must be a way of combining "([^\;])" and "([;])" to get what I require.

public static List parse(String data) {

List parsedRecords = new List();

String[] records = data.split(";");

for (String record : records) {

String[] fields = data.split("-");

parsedRecords.add(new parsedRecord(fields));

}

return parsedRecords;

}

Thanks very much in advance.

解决方案

You could perhaps refine your regular expression used with split like this:

split("[^\\];")

To split at anything that is a ";" but not if before that there is a "\". And the same for the dashes:

split("[^\\]-")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值