【问题标题】:Java RegEx find, except when between quotesJava RegEx 查找,引号之间除外
【发布时间】:2013-11-15 06:44:55
【问题描述】:

我需要一个 Java RegEx 来拆分,或在字符串中查找某些内容,但排除双引号之间的内容。我现在要做的是:

String withoutQuotes = str.replaceAll("\\\".*?\\\"", "placeholder");
withoutQuotes = withoutQuotes.replaceAll(" ","");

但这对indexOf来说效果不好,我还需要能够拆分,例如:

String str = "hello;world;how;\"are;you?\""
String[] strArray = str.split(/*some regex*/);
// strArray now contains: ["hello", "world", "how", "\"are you?\"]
  • 报价总是平衡的
  • 可以使用\" 转义引号

感谢任何帮助

【问题讨论】:

  • 引号总是平衡的吗?这些引号可以使用\" 转义吗
  • 哦,对不起,忘了说。是的,引号是平衡的,是的,它们可以用 \" 转义
  • 你是什么意思第一件事不能很好地与 indexOf 一起工作?
  • 如果你保存索引,然后在原始字符串上使用它,它不会是相同的字符,因为占位符可能与原始引用文本的长度不同

标签: java regex split quotes


【解决方案1】:

好的,这是一个适合你的代码:

String str = "a \"hello world;\";b \"hi there!\"";
String[] arr = str.split(";(?=(([^\"]*\"){2})*[^\"]*$)");
System.out.println(Arrays.toString(arr));

如果分号后跟偶数个双引号(这意味着; 在引号之外),则此正则表达式会找到分号。

输出:

[a "hello world;", b "hi there!"]

PS:它不会处理像\"这样的转义引号

【讨论】:

  • 它工作得几乎完美,但是当我尝试这个时:a "hello world;"; b "hi there!";,它返回["a "hello world"",""","b "hi there""]
  • 你能给我一个有效的Java字符串值,我可以试试。
  • 给你:a \"hello world;\";b \"hi there!\"
  • 通过It doesn't take care of escaped quotes like \"查看更新的答案
  • 有没有简单的方法来添加它?否则我会想一些其他的方法来实现这一点
【解决方案2】:

重新提出这个问题,因为它有一个没有提到的简单正则表达式解决方案。 (在为regex bounty quest 做一些研究时发现了你的问题。)

\"[^\"]*\"|(;)

交替的左侧匹配完整的引号字符串。我们将忽略这些匹配。右侧将分号匹配并捕获到第 1 组,我们知道它们是正确的分号,因为它们没有被左侧的表达式匹配。

这是工作代码(见online demo):

import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;

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

String subject = "hello;world;how;\"are;you?\"";
Pattern regex = Pattern.compile("\"[^\"]*\"|(;)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
    if(m.group(1) != null) m.appendReplacement(b, "SplitHere");
    else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
String[] splits = replaced.split("SplitHere");
for (String split : splits) System.out.println(split);
} // end main
} // end Program

参考

  1. How to match pattern except in situations s1, s2, s3
  2. How to match a pattern unless...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-05
    • 2019-10-17
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多