如何拆分逗号分隔的字符串,而忽略转义的逗号? [英] How to split a comma separated String while ignoring escaped commas?
问题描述
我需要编写一个扩展版本的StringUtils.commaDelimitedListToStringArray函数,它获得一个额外的参数:转义字符
所以调用我的:
commaDelimitedListToStringArray(test,test\\\,test\\,test,test,\\)
应返回:
[test,test,test,test,test]
我目前尝试使用String.split()使用正则表达式拆分String:
String [] array = str.split([^ \\\\],);
但返回的数组是:
[tes,test\,test\,tes,test]
任何想法?
正则表达式
[^ \\],
表示匹配不是反斜杠后跟逗号的字符 - 这就是为什么 t,
等模式匹配的原因,因为 t
是不是反斜杠的字符。
我认为您需要使用某种 negative lookbehind ,捕获未包含 \
的,
字符,例如
(?<!\\),
(注意,我有意没有双重转义反斜杠,使其更易读)
I need to write a extended version of the StringUtils.commaDelimitedListToStringArray function which gets an additional parameter: the escape char.
so calling my:
commaDelimitedListToStringArray("test,test\\,test\\,test,test", "\\")
should return:
["test", "test,test,test", "test"]
My current attempt is to use String.split() to split the String using regular expressions:String[] array = str.split("[^\\\\],");
But the returned array is:
["tes", "test\,test\,tes", "test"]
Any ideas?
解决方案The regular expression
[^\\],
means "match a character which is not a backslash followed by a comma" - this is why patterns such as
t,
are matching, becauset
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屋!