Momo
Momo

Reputation: 3810

Remove surrounding character when followed by another character

I have the following characters:

{"foo":"bar"}

The goal of the regex is to find surrounding double-quotes when the last one is followed by a colon. In the mentioned case, it should find the first two double-quotes alone, since the last of the two is followed by a colon.

I currently have the following regex: ((")+[^"]+"+:), which finds "foo":. What should I change so that it can select the double-quotes alone?

Upvotes: 1

Views: 54

Answers (4)

Sebastian Proske
Sebastian Proske

Reputation: 8413

You could just match "+([^"]+)"+(?=:) and replace it with $1 as shown in this example. However this doesn't take into account any escaping and you might consider @Jan s comment of using a JSON-library.

Upvotes: 1

crackmigg
crackmigg

Reputation: 5881

I would do it like this:

/\{"([^"]+)"\s*:\s*"([^"]+)"\}/g

and replace with:

{$1:"$2"}

See demo: https://regex101.com/r/aX6lH8/1

Upvotes: 0

Jan
Jan

Reputation: 43169

Simply use a positive lookahead like so:

"([^"]+)"(?=:)

See a demo on regex101.com.

Upvotes: 0

Shafizadeh
Shafizadeh

Reputation: 10340

I'm not sure I get you right .. But try this:

/{"(.*)(?:"):/

Online Demo

Upvotes: 1

Related Questions