bflemi3
bflemi3

Reputation: 6790

Regex to remove space after first parenthesis and before last parenthesis

I need to remove the space after the first parenthesis and the space before the last parenthesis of the following strings:

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 )

The results would be:

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)

I can get the first space but having issues with the last space.

^\w*\s*\((\s*)

Please see regex101 for my attempt

Upvotes: 0

Views: 682

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382170

Just .replace(/\(\s*(.*?)\s*\)/,"($1)"))

The idea is to use a non greedy capture, .*?, to capture what's between the two parts to replace.

Demonstration:

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>

Upvotes: 2

anubhava
anubhava

Reputation: 785276

You can use this regex with captured regex for replacements:

String repl = str.replace(/^([^(]+\()\s*([^)]+?)\s*\)/, "$1$2)");

Updated Regex Demo

Upvotes: 3

TimoStaudinger
TimoStaudinger

Reputation: 42460

Simple and understandable solution, even though not necessarily optimal:

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)"

Upvotes: 0

Related Questions