如何在忽略转义逗号的同时拆分逗号分隔的字符串? [英] How to split a comma separated String while ignoring escaped commas?
问题描述
我需要编写 StringUtils.commaDelimitedListToStringArray 函数的扩展版本,该函数获得一个附加参数:转义字符.
I need to write a extended version of the StringUtils.commaDelimitedListToStringArray function which gets an additional parameter: the escape char.
所以叫我的:
commaDelimitedListToStringArray("test,test\,test\,test,test", "\")
应该返回:
["test", "test,test,test", "test"]
我目前的尝试是使用 String.split() 使用正则表达式拆分字符串:
My current attempt is to use String.split() to split the String using regular expressions:
String[] array = str.split("[^\\],");
但是返回的数组是:
["tes", "test,test,tes", "test"]
有什么想法吗?
推荐答案
正则表达式
[^\],
表示匹配一个不是反斜杠后跟逗号的字符"——这就是为什么诸如 t,
之类的模式匹配的原因,因为 t
是一个字符不是反斜杠.
means "match a character which is not a backslash followed by a comma" - this is why patterns such as t,
are matching, because t
is a character which is not a backslash.
我认为你需要使用某种负向后视,来捕捉,
前面没有 而不捕获前面的字符,类似于
I think you need to use some sort of negative lookbehind, to capture a ,
which is not preceded by a without capturing the preceding character, something like
(?<!\),
(顺便说一句,请注意,我故意没有对反斜杠进行双重转义以使其更具可读性)
(BTW, note that I have purposefully not doubly-escaped the backslashes to make this more readable)
这篇关于如何在忽略转义逗号的同时拆分逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!