0

I'm trying to find-and-replace instances where consecutive commas appear throughout a string; replacing them w/ something like ",N/A,". I was using a very simple /,,/g pattern, and that works on things like ",,abc" and ",,,,abc" (with even numbers of commas). However, it doesn't catch things like ",,,abc". That's because the first two commas are considered a match, and then the third comma is just considered part of a new ",abc" string. Is there a way to handle this w/ a RegEx pattern or options? Otherwise, I'm going to need to perform multiple searches.

FWIW - I'm working in JavaScript, but I'm guessing this is just a general RegEx question/answer.

WEFX
  • 8,298
  • 8
  • 66
  • 102

1 Answers1

0

The reason why /,,/g only matches once with three commas is because the global match restarts after the position of the final consumed characters. You need a way to match the pattern of ,, without consuming those characters for pattern matching purposes.

If your language supports it, use a positive lookahead. A positive lookeahead lets a regex match some additional characters, but not consume them in the pattern.

/,(?=,)/g

In English, this means:

,     # match a comma, then
(?=   #start a group that must exist, and if so, isn't consumed by the pattern,
 ,    # a comma
)

See more about this here: https://www.regular-expressions.info/lookaround.html

Javascript supports positive lookahead. :)

Robert P
  • 15,707
  • 10
  • 68
  • 112