Home > Mobile >  Replace double quotes with single quotes between pairs of square brackets
Replace double quotes with single quotes between pairs of square brackets

Time:10-03

a = """abcda"sd"asd["first", "last", "middle", "dob", "gender"]abcda"sd"asd"""
a = re.sub("\[(\".*?\",?)*\]", r'\g<0>'.replace('"', ""), a)
print(a)

I am trying to replace the double qoutations in the provided string. Is the method i am using correct? Is there another method (one-liner preffered) to obtain the desired result.

Desired string result as below

"""abcda"sd"asd['first', 'last', 'middle', 'dob', 'gender']abcda"sd"asd"""

I need to replace double qoutes only inside the brackets"[]"

CodePudding user response:

You can omit the capture group from the pattern as you are replacing on the whole match.

The pattern \[(\".*?\",?)*\] can also match a , at the end, and uses a non greedy match between the double quotes.

What you might do is use a negated character class [^"]* instead to match all between the double quotes, and optionally repeat a non capture group(?:\s*,\s*"[^"]*")* with a leading comma to not allow a comma at the end.

re.sub can use a lambda where you might also do the replacement of the double quotes.

import re

a = """abcda"sd"asd["first", "last", "middle", "dob", "gender"]"""
a = re.sub(r'\["[^"]*"(?:\s*,\s*"[^"]*")*', lambda m: m.group().replace('"', "'"), a)
print(a)

Output

abcda"sd"asd['first', 'last', 'middle', 'dob', 'gender']

CodePudding user response:

You may use the newer regex module and \G as in:

(?:\G(?!\A)[^"\]\[]*|\[)\K"

See a demo on regex101.com.


In terms of Python this could be

import regex as re

text = """abcda"sd"asd["first", "last", "middle", "dob", "gender"]abcda"sd"asd"""
pattern = re.compile(r'''(?:\G(?!\A)[^"\]\[]*|\[)\K"''')

text = pattern.sub("'", text)

print(text)

And would yield

abcda"sd"asd['first', 'last', 'middle', 'dob', 'gender']abcda"sd"asd

CodePudding user response:

You can use the method replace. a.replace('"', "'")

  • Related