如何使用之前没有转义字符的字符拆分java字符串

时间:2022-08-28 21:45:27

I've a string like this:

我有一个像这样的字符串:

a=b\=c

and I need to split it using java split method such that my assertion does not throw an exception:

我需要使用java split方法拆分它,这样我的断言不会抛出异常:

String[] res = "a=b\\=c".split("SPLIT_REGEX");
assert (res[0].equals("a") && res[1].equals("b\\=c"));

I've tried [^\\]= as SPLIT_REGEX but it does not give me the desired answer. Could anybody tell me what would be the correct regex for my goal?

我试过[^ \\] =作为SPLIT_REGEX,但它没有给我想要的答案。谁能告诉我,我的目标是什么样的正确正则表达式?

1 个解决方案

#1


2  

You can use a negative lookbehind before = to skip splitting in \=:

您可以在=之前使用负向lookbehind来跳过\ =中的拆分:

String res = "a=b\\=c";
String[] toks = res.split("(?<!\\\\)=");
//=> ["a", "b\\=c"]

(?<!\\\\) is negative lookahead that asserts failure when \ is present before =

(?

#1


2  

You can use a negative lookbehind before = to skip splitting in \=:

您可以在=之前使用负向lookbehind来跳过\ =中的拆分:

String res = "a=b\\=c";
String[] toks = res.split("(?<!\\\\)=");
//=> ["a", "b\\=c"]

(?<!\\\\) is negative lookahead that asserts failure when \ is present before =

(?