我不太擅长正则表达式,有人可以给我一个正则表达式(在 Java 中使用)来选择不在两个引号之间的所有空格吗?我正在尝试从字符串中删除所有此类空格,因此任何解决方案都可以这样做。
例如:
(this is a test "sentence for the regex")
应该变成
(thisisatest"sentence for the regex")
最佳答案
这是一个有效的正则表达式替换:
\s+(?=([^"]*"[^"]*")*[^"]*$)
将替换:
(this is a test "sentence for the regex" foo bar)
与:
(thisisatest"sentence for the regex"foobar)
请注意,如果引号可以转义,则更冗长的正则表达式会起作用:
\s+(?=((\\[\\"]|[^\\"])*"(\\[\\"]|[^\\"])*")*(\\[\\"]|[^\\"])*$)
替换输入:
(this is a test "sentence \"for the regex" foo bar)
与:
(thisisatest"sentence \"for the regex"foobar)
(请注意,它也适用于转义的退格:(thisisatest"sentence\\\"for the regex"foobar)
)
不用说 (?),这确实不应该用于执行这样的任务:它让人眼花缭乱,它在二次时间内执行任务,而存在一个简单的线性解决方案。
编辑
快速演示:
String text = "(this is a test \"sentence \\\"for the regex\" foo bar)";
String regex = "\\s+(?=((\\\\[\\\\\"]|[^\\\\\"])*\"(\\\\[\\\\\"]|[^\\\\\"])*\")*(\\\\[\\\\\"]|[^\\\\\"])*$)";
System.out.println(text.replaceAll(regex, ""));
// output: (thisisatest"sentence \"for the regex"foobar)
关于java - 正则表达式选择所有不在引号中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9577930/