使用Java解析包含转义字符的字符串 [英] Parsing a string containing escaped characters using Java

查看:1428
本文介绍了使用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<ParsedRecord> parse(String data) {
    List<ParsedRecord> parsedRecords = new List<ParsedRecord>();
    String[] records = data.split(";");
    for (String record : records) {
        String[] fields = data.split("-");
        parsedRecords.add(new parsedRecord(fields));
    }
    return parsedRecords;
}

非常感谢提前。

推荐答案

你可以用这样的方式改进你用于拆分的正则表达式:

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("[^\\]-")

这篇关于使用Java解析包含转义字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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