Graham Graham - 5 days ago 5
Javascript Question

Regex for replacing character within quotes

I have two test strings:

1+":"+2:xyz
1+"a:fb"+2:xyz


I am trying to replace the : which is between quotes.

I tried this:

(".*):(.*")


replacing with:

$1Q$2


but I end up with this:

1+"Q"+2:xyz
1+"Q"+2:xyz


but I want to end up with this:

1+"Q"+2:xyz
1+"aQfb"+2:xyz


Can somebody help me out please. Must work in Javascript.

EDIT:

I have switched my testing tool to one that works properly (namely doing it directly in javascript in a browser).

This now works:

var str = '1+"a:fb"+2:xyz';
var res = str.replace(/(".*):(.*")/g, "$1Q$2");


but what if I have two : in two sets of quotes, like so:

1+"a:fb"+2+":"


I now get this result:

1+"a:fb"+2+"Q":xyz

Answer

Effectively you are trying to replace a pattern that consists of three parts:

  1. a bit that starts with a " and contains neither " nor :
  2. a :
  3. a bit that contains neither " nor : and ends with a "

so the expression would look like:

"([^:"]*):([^:"]*)"

substituted for "$1Q$2" this results in

1+"Q"+2:xyz
1+"aQfb"+2:xyz

The reason why yours did not work properly lies in greedy matching.

Comments