使用String.split时转义逗号 [英] Escape comma when using String.split

查看:157
本文介绍了使用String.split时转义逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一些超级简单的解析o日志文件,所以我使用 String.split 这样的方法:

I'm trying to perform some super simple parsing o log files, so I'm using String.split method like this:

String [] parts = input.split(",");

适用于以下输入:

a,b,c

type=simple, output=Hello, repeat=true 

只是说点什么。

如何逃避逗号,所以它与中间逗号不匹配?

How can I escape the comma, so it doesn't match intermediate commas?

例如,如果我想在其中一个部分中加入逗号:

For instance, if I want to include a comma in one of the parts:

type=simple, output=Hello, world, repeate=true

我想的是:

type=simple, output=Hello\, world, repeate=true

但我不知道如何创建拆分以避免匹配逗号。

But I don't know how to create the split to avoid matching the comma.

I尝试过:

String [] parts = input.split("[^\,],");

但是,好吧,不行。

推荐答案

您可以使用负面看后面

String[] parts = str.split("(?<!\\\\), ");

基本上它表示,拆分每个 前面没有反斜杠

Basically it says, split on each ", " that is not preceeded by a backslash.

String str = "type=simple, output=Hello\\, world, repeate=true";
String[] parts = str.split("(?<!\\\\), ");
for (String s : parts)
    System.out.println(s);

输出:

type=simple
output=Hello\, world
repeate=true

ideone.com链接

如果您碰巧遇到未转义的逗号分隔值,您可以执行以下(类似)hack:

If you happen to be stuck with the non-escaped comma-separated values, you could do the following (similar) hack:

String[] parts = str.split(", (?=\\w+=)");

哪个分区每个 后跟一些单词字符和一个=

Which says split on each ", " which is followed by some word-characters and an =

ideone.com链接

这篇关于使用String.split时转义逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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