我需要删除第一个括号后面的空格和下面字符串的最后一个括号之前的空格:
POINT ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT ( -68.1712366598 -16.5122344611 )
POINT Z ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT Z ( -68.1712366598 -16.5122344611 )
结果将是:
POINT (-68.1712366598 -16.5122344611 4124.6247727228)
POINT (-68.1712366598 -16.5122344611)
POINT Z (-68.1712366598 -16.5122344611 4124.6247727228)
POINT Z (-68.1712366598 -16.5122344611)
我可以获得第一个空格但是最后一个空格有问题。
^\w*\s*\((\s*)
请参阅regex101了解我的尝试
答案 0 :(得分:3)
您可以将此正则表达式与捕获的正则表达式一起用于替换:
String repl = str.replace(/^([^(]+\()\s*([^)]+?)\s*\)/, "$1$2)");
答案 1 :(得分:2)
只需.replace(/\(\s*(.*?)\s*\)/,"($1)"))
我们的想法是使用非贪婪捕捉.*?
来捕捉要替换的两个部分之间的内容。
演示:
document.getElementById("output").innerHTML = document.getElementById("input")
.innerHTML.split("\n")
.map(line=>line.replace(/\(\s*(.*?)\s*\)/,"($1)"))
.join("\n");

<pre id=input>
POINT ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT ( -68.1712366598 -16.5122344611 )
POINT Z ( -68.1712366598 -16.5122344611 4124.6247727228 )
POINT Z ( -68.1712366598 -16.5122344611 )
</pre>
<pre id=output>
</pre>
&#13;
答案 2 :(得分:0)
简单易懂的解决方案,即使不一定是最佳解决方案:
var input = 'POINT ( -68.1712366598 -16.5122344611 4124.6247727228 )';
var formatted = input
.replace(/\( +/g, '(')
.replace(/ +\)/g, ')');
console.log(formatted); // "POINT (-68.1712366598 -16.5122344611 4124.6247727228)"
&#13;