-3

I have this string

string value = "1: [polo, pola, pilo], 2: [molo, mola, moli], 3: [colo, cola, coli]"
// result should be:  "1: [polo. pola. pilo], 2: [molo. mola], 3: [colo. cola. coli. colu]"

i want a regex to replace the ',' between [ ] by '.' the output has to be like this

"1: [polo pola pilo], 2: [molo mola moli], 3: [colo cola coli]"

what i tried.

    const regex = /[,]\s\D/gm;
    
    result = result.replace(regex, "");

my regex is not good.
Deus Ralph
  • 23
  • 6
  • 3
    Great, what have you tried so far? Show us your attempts at solving the problem, and where *specifically* in those attempts you're getting stuck. – esqew Jun 22 '20 at 17:58
  • easiest solution: use a replacer function and two levels of regex replace – user120242 Jun 22 '20 at 18:08
  • two levels of regex ? – Deus Ralph Jun 22 '20 at 18:17
  • Must use regex? Why "."s? Here's a way without regex: sss=s.split("], ").join("]").split(",").join(".").split("]").join("], ") first split removes the special "], " so the commas won't change, joining with only "]". second split removes the commas, joining with "." instead. third split re-places the saved with "]" with the original "], ".... – iAmOren Jun 22 '20 at 18:18
  • assumes no nested brackets: `str.replace(/\[.*?\]/g, x=>x.replace(/,/g,'.'))` – user120242 Jun 22 '20 at 18:32
  • actually if nested brackets aren't a concern this is good enough `value.replace(/,(?=[^[\]]*\])/g,'.')` – user120242 Jun 22 '20 at 18:37
  • Does this answer your question? [Replace comma in parentheses using regex in java](https://stackoverflow.com/questions/3697139/replace-comma-in-parentheses-using-regex-in-java) – user120242 Jun 22 '20 at 18:39
  • Thanks a lot guys. you saved my life.. LOL – Deus Ralph Jun 22 '20 at 18:57

1 Answers1

0

This assumes you have no unmatched brackets, and no nested brackets.
Based on above assumptions:
If comma isn't followed by any brackets other than an ending bracket, it must be inside a bracket.

value = "1: [polo, pola, pilo], 2: [molo, mola, moli], 3: [colo, cola, coli]"
console.log(
value.replace(/,(?=[^[\]]*\])/g,'.')
)

If you need to account for unmatched brackets:

value.replace(/\[.*?\]/g, x=>x.replace(/,/g,'.'))

First finds matching [ ] brackets, then replaces all commas in that string in the replacer function before returning the desired replacement string.


If you need nested brackets, you will need to use a stack:
JavaScript regex that ignores matches nested inside parentheses
Instead of ignoring enclosed strings, you'll want to adjust it to replace commas in the enclosures. For my answer in there, it would be if stack.length > 0 and comma, replace with period.

user120242
  • 14,918
  • 3
  • 38
  • 52