将Java中的字符串拆分为“;”,而不是“\\;” [英] Splitting a string in Java on ";", but not on "\\;"
问题描述
在Java中,我尝试使用 String.split()
方法在上分割字符串;
,但不在\\\\;
。 (2个反斜杠后跟分号)
In Java I try try to use the String.split()
method splitting a string on ";"
, but not on "\\\\;"
. (2 back-slashes followed by a semi-colon)
Ex:aa; bb; cc \\; dd; ee \\ \ ;;; ff
应分成;
aa
bb
cc\\;dd
ee\\;
ff
如何使用正则表达式完成此操作?
How do I accomplish this using a regular expression?
Markus
推荐答案
使用
"aa;bb;cc\\;dd;ee\\;;ff".split("(?<!\\\\);");
(?<!...)被称为零宽度lookbehind。在英语中,您将拆分所有;
字符,其中 NOT 前面有双斜杠,而不实际匹配双斜杠。四重斜杠是将反斜杠转义为正则表达式解析器。然后,拆分中使用的实际正则表达式将为:
(?<!...) is called a "zero-width lookbehind". In English, you're splitting on all ;
characters that are NOT preceded by a double slash, without actually matching the double slash. The quadruple slash is to escape backslashes to the regex parser. The actual regular expression used in the split would then read:
(?<!\\);
这篇关于将Java中的字符串拆分为“;”,而不是“\\;”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!