Home > Enterprise >  Eliminate the last comma in curly braces using regex
Eliminate the last comma in curly braces using regex

Time:08-31

I'm trying to figure out how to take out the last comma in curly braces using regex. I have the following example:

cypher_query = 'match n:chocolate{chocolate:$chocolate, icecream:'snowcone', donut:$donut, chocolate:$chocolate,}) return n';

with the goal of getting (takes out that last comma in the curly braces):

cypher_query = 'match n:chocolate{chocolate:$chocolate, icecream:'snowcone', donut:$donut, chocolate:$chocolate}) return n';

Using regex, I've tried the following:

import re
new_query = re.sub(r'\{\,$\}', '', cypher_query)

Any ideas?? Thanks so much!

CodePudding user response:

So this?

import re
new_query = re.sub(',}', '}', cypher_query) #looks for ,} and replaces it with just a }

CodePudding user response:

You can capture the part starting from the { to before the comma in group 1.

Then match ,} and replace with the group 1 value \1 and only }

({[^{}]*),}

Regex demo

import re

cypher_query = 'match n:chocolate{chocolate:$chocolate, icecream:\'snowcone\', donut:$donut, chocolate:$chocolate,}) return n';
new_query = re.sub(r'({[^{}]*),}', r'\1}', cypher_query)
print(new_query)

Output

match n:chocolate{chocolate:$chocolate, icecream:'snowcone', donut:$donut, chocolate:$chocolate}) return n
  • Related