gpt4 book ai didi

java Regex - 忽略引号?

转载 作者:行者123 更新时间:2023-12-02 07:45:57 24 4
gpt4 key购买 nike

我想捕获单引号文本,但是转义单引号 (\') 不应被视为分隔符,例如:

This 'wasn\'t the best' day

应该返回

  • wasn't the best

谢谢。

我已经尝试过这个:

    public static List<String> cropQuoted (String s) {

Pattern p = Pattern.compile("\\'[^']*\\'");
Matcher m = p.matcher(s);
ArrayList found = new ArrayList();
while(m.find()){
found.add(m.group().replaceAll("\'", ""));
System.out.println(m.group().replaceAll("\'", ""));
}
return found;
}

但它无法捕捉到“\'best'days'to come”

最佳答案

(?<!\\\\)'表示“每个',前面没有\

使用它我们可以创建类似 (?<!\\\\)'.*?(?<!\\\\)' 的东西

让我们测试一下

    String s="This 'wasn\\'t the best' day. Another 't\\'es\\'t Test' t\\'est";
System.out.println(s.replaceAll("(?<!\\\\)'.*?(?<!\\\\)'", "X"));
//out -> This X day. Test X t\'est

这是你要找的吗?

关于java Regex - 忽略引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865550/

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