0
str = '{"name": "John", "company": "AB"C corp", "id": "12g: "123 12-12"}'

B"C replace with empty string ''

g: "1 replace with empty string ''

Required string

str = '{"name": "John", "company": "A corp", "id": "1223 12-12"}'

What is the regex for this?

Tried

import re

str = re.sub(r'^[a-zA-Z0-9: "0-9]$', "", str)

Examples:

Valid: '"name": "John"'
Invalid: '"nam"e": "Jo"hn"'

Valid: '"id": "12A"'
Invalid: 'id: "12A"'
6
  • Regex? Why not str.replace('B"C', '').replace('g: "1', '')? Commented Feb 12, 2018 at 4:41
  • It can be any Letter / number and not B"C or g: "1. Hence regex Commented Feb 12, 2018 at 4:42
  • 2
    Can you please state your requirements accurately? What can be any letter/number? It's impossible to tell if you want \w: "\w or \w: "\d or [a-z]: "\d or one of the other 50 possible regexes. Commented Feb 12, 2018 at 4:45
  • Something like this would work for your cases [A-Za-z][^"]*"\w but as @Aran-Fey says, the requirements are not clear Commented Feb 12, 2018 at 4:47
  • Examples: Valid: '"name": "John"' Invalid: '"nam"e": "Jo"hn"' Valid: '"id": "12A"' Invalid: 'id: "12A"' Commented Feb 12, 2018 at 4:51

2 Answers 2

2

You can try this!

check if you have a character, (a colon or space or both) that is followed by " and by a \w(character or number).

>>> s
'{"name": "John", "company": "AB"C corp", "id": "12g: "123 12-12"}'
>>> re.sub('\w[: ]*"\w','',s)
'{"name": "John", "company": "A corp", "id": "1223 12-12"}'
Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean \W"\W and \w: "\d are the only cases you're worrying about?

Then try this:

str = re.sub(r'([a-zA-Z](\: )?"[A-Z0-9])', "", str)

2 Comments

1. no need for capturing group 2. no need to escape :
How to remove double quotes inside a double quotes. Ex "{"name": "John"}" needs to become "{'name': 'John'}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.