Java RegEx 查找,引号之间除外

Dir*_*irk 4 java regex quotes split

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

String withoutQuotes = str.replaceAll("\\\".*?\\\"", "placeholder");
withoutQuotes = withoutQuotes.replaceAll(" ","");
Run Code Online (Sandbox Code Playgroud)

但这不适用于 indexOf,而且我还需要能够拆分,例如:

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

任何帮助表示赞赏

anu*_*ava 5

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

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

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

输出:

[a "hello world;", b "hi there!"]
Run Code Online (Sandbox Code Playgroud)

PS:它不会处理转义的引号,例如\"