gpt4 book ai didi

java - 正则表达式仅针对非转义字符进行分割

转载 作者:行者123 更新时间:2023-11-30 06:20:42 24 4
gpt4 key购买 nike

我有一个字符串,需要在某些字符上拆分,但如果它们被转义则不需要拆分。到目前为止,我使用了正则表达式,但意识到如果转义字符本身被转义,我就会遇到麻烦。那么如果 : 是分割字符并且 ?我期望这种行为的转义字符

a:b?:c??:d???:e????:f

变成了

a
b?:c??
d???:e????
f

底线:

  • 只有当 : 前面有偶数个 ? 时,才会发生分割。或者没有?
  • 全部?必须保留。

有什么想法吗?

最佳答案

代码

See regex in use here

(?<!\?)(?:\?{2})*\K:

其他变体:

(?:^|[^?])(?:\?{2})*\K:       Doesn't use lookbehind
(?<=(?:^|[^?])(?:\?{2})*): Doesn't use \K, uses variable length lookbehind

说明

  • (?<!\?)负向后查找确保前面的内容不匹配 ?
  • (?:\?{2})*匹配??任意次数
  • \K重置图案的起点。任何之前消耗的角色都不再包含在最终比赛中
  • :按字面意思匹配
<小时/>

编辑

在我的回答下的评论中,OP提到使用的语言是 。由于Java不支持\K或可变宽度lookbehinds,我决定将正则表达式(以及 Matcher 对象的 end() 方法)与 substring() 一起使用方法。

代码

See code in use here

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{

private static List<Integer> indices = new ArrayList<Integer>();
private static List<String> result = new ArrayList<String>();

public static void main (String[] args) throws java.lang.Exception
{

String str = "a:b?:c??:d???:e????:f";

Pattern pattern = Pattern.compile("(?<!\\?)(?:\\?{2})*:");
Matcher matcher = pattern.matcher(str);

while(matcher.find()) {
result.add(str.substring(getLastIndex(), matcher.end() - 1));
indices.add(matcher.end());
}
result.add(str.substring(getLastIndex()));
System.out.print(result);
}

private static int getLastIndex() {
if(indices.isEmpty()) {
return 0;
} else {
return indices.get(indices.size() - 1);
}
}
}

说明

  1. 循环匹配正则表达式模式 (?<!\?)(?:\?{2})*: .
  2. 获取上一个索引(或 0 如果不存在)到 Matcher.end() 的子字符串并将其添加到 result列表。
  3. 添加Matcher.end() (对于当前匹配)到 indices列表。
  4. 上述循环结束后,从 indices 中最后获取的索引处获取子字符串list 到字符串末尾并将其添加到 result列表。

关于java - 正则表达式仅针对非转义字符进行分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48211069/

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