Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - wrap all integers in double quotes

Tags:

regex

I want to turn this string;

0000,0767,"078", 0785, "0723",23487, 345 , 07334

Into this string;

"0000","0767","078", "0785", "0723","23487", "345" , "07334"

This is the closest I can get to it, I always get a bit confused with negative lookups and such when it comes to regex.

[^"\d,]?(\d+) and a replace with "$1" - https://regex101.com/r/qVQYA7/1

unfortunately this results in double wrapped quotes for integers that already have double quotes around them, like so;

"0000","0767",""078"","0785", ""0723"","23487","345" ,"07334"

The pseudo logic is; look for any integers that don't already have double quotes around them, and add double quotes. Leave any spacing in between commas as is.

like image 476
Novocaine Avatar asked Mar 11 '23 21:03

Novocaine


2 Answers

You can simply search for "?(\d+)"? and replace it with "$1". If there are " present, they are matched but not contained in the group.

like image 198
Sebastian Proske Avatar answered Mar 19 '23 13:03

Sebastian Proske


You can use lookarounds in your regex to avoid matching quoted numbers:

(?<!")(\b\d+\b)(?!")

Updated Regex Demo

RegEx Breakup:

(?<!")   # Negative lookbehind to skip the match if previous character is "
(        # captured group #1 open
   \b    # assert word boundary
   \d+   # match 1 or more digits
   \b    # assert word boundary
)        # captured group close
(?!")    # Negative lookahead to skip the match if next character is "

If you're using PCRE then you can use this PCRE verb:

"\d+"(*SKIP)(*F)|(\d+)
like image 28
anubhava Avatar answered Mar 19 '23 12:03

anubhava