Regular expression to replace spaces between numbers with a comma

6.6k Views Asked by At

I have a huge list of the following in a large file that contains information about every country in the world.

They are arrays of temperature data, sometimes the spaces vary in length.

[23.5  26.3  29.3  31.9  32.8  31.2  28.8  27.8  28.4  29  26.6  23.7]

I'm attempting to use sublime to write a regular expression but I cannot get my head around them.

So far the closest thing I've got is:

( \S+)\(.+ )

How would one write a regular expression replacing the line to look like this:

[23.8,25.5,27.2,28.3,29.3,29.5,28.7,28.1,28.2,28.9,27.2,24.4]

Any help would be great thanks.

**Edit I'm using sublime text.

2

There are 2 best solutions below

3
On BEST ANSWER

You can use this: (?<=\d)\s+(?=\d|\-), using find and replace all in sublime text.

(?<=\d) is a positive lookbehind, it checks if the previous symbol is a digit, without actually matching it.

(?=\d) is a positive lookahead, same thing - checks if the following symbol is a digit, without actually matching it.

Just FYI, lookbehinds aren't supported in javascript, but that doesn't matter in this case.

https://regex101.com/r/qX1qF5/7 for easier fiddling with it.

7
On

Just do:

(\d)\s+(\d)

And the in the replace:

$1,$2

RegEx Answer

How it works:

  1. (\d) - Find a digit and capture it
  2. \s+ - that has one or more spaces after it.
  3. (\d) - and is followed by another digit and capture it.

Doing a "Replace All" with those settings turns this:

[23.5  26.3  29.3  31.9  32.8  31.2  28.8  27.8  28.4  29  26.6  23.7]

Into:

[23.5,26.3,29.3,31.9,32.8,31.2,28.8,27.8,28.4,29,26.6,23.7]

Note that if there are any other places in your data file that have a digits followed by some number of white space characters followed by another digit that will as be affected. If that happens there are other ways to refine this but it would require seeing samples of the rest of the data. And, at some point, if there is too much going on, trying to solve it with a single RegEx may be impossible without effecting other data.