gpt4 book ai didi

java/scala : Regex for skipping odd number of backslash while splitting a String?

转载 作者:太空宇宙 更新时间:2023-11-04 11:00:58 25 4
gpt4 key购买 nike

这是我的要求:

Input1: adasd|adsasd\|adsadsadad|asdsad
output1: Array(adasd,adsasd\|adsadsadad,asdsad)

Input2: adasd|adsasd\\|adsadsadad|asdsad
output2: Array(adasd,adsasd\\,adsadsadad,asdsad)

Input3: adasd|adsasd\\\|adsadsadad|asdsad
output3: Array(adasd,adsasd\\\|adsadsadad,asdsad)

我正在使用这段代码:

val delimiter =Pattern.quote("|")
val esc = "\\"
val regex = "(?<!" + Pattern.quote(esc) + ")" + delimiter

但这并不适用于所有情况。

解决这个问题的最佳解决方案是什么?

最佳答案

不要拆分,而是使用此正则表达式进行匹配:

(?<=[|]|^)[^|\\]*(?:\\.[^|\\]*)*

Java Code Demo

Java 代码:

final String[] input = {"adasd|adsasd\\|adsadsadad|asdsad",
"adasd|adsasd\\\\|adsadsadad|asdsad",
"adasd|adsasd\\\\\\|adsadsadad|asdsad"};

final String regex = "(?<=[|]|^)[^|\\\\]*(?:\\\\.[^|\\\\]*)*";
final Pattern pattern = Pattern.compile(regex);
Matcher matcher;

for (String string: input) {
matcher = pattern.matcher(string);
System.out.println("\n*** Input: " + string);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
}

输出:

*** Input: adasd|adsasd\|adsadsadad|asdsad
adasd
adsasd\|adsadsadad
asdsad

*** Input: adasd|adsasd\\|adsadsadad|asdsad
adasd
adsasd\\
adsadsadad
asdsad

*** Input: adasd|adsasd\\\|adsadsadad|asdsad
adasd
adsasd\\\|adsadsadad
asdsad

关于java/scala : Regex for skipping odd number of backslash while splitting a String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46895348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com