1
input = "'Siva', ['Aswin','latha'], 'Senthil',['Aswin','latha']" 

expected output:

"'Siva', [Aswin,latha], 'Senthil',[Aswin,latha]"

I have used positive lookbehind and lookahead but its not working.

pattern

(?<=\[)\'+(?=\])
3
  • Your pattern will match ['] or contain multiple ' Commented May 21, 2021 at 4:27
  • 1
    What are you actually trying to accomplish here? Commented May 21, 2021 at 4:47
  • Can you have a string like "'Siva', ['Aswin','latha'], 'Senthil',['[Aswin','[latha]']" ? Commented May 21, 2021 at 8:28

4 Answers 4

2

We can use re.sub here with a callback lambda function:

inp = "'Siva', ['Aswin','latha'], 'Senthil',['Aswin','latha']"
output = re.sub(r'\[.*?\]', lambda x: x.group().replace("'", ""), inp)
print(output)

This prints:

'Siva', [Aswin,latha], 'Senthil',[Aswin,latha]
Sign up to request clarification or add additional context in comments.

Comments

1
import re
input = "'Siva', ['Aswin','latha'], 'Senthil',['Aswin','latha']"


print(re.sub(r"(?<=\[).*?(?=\])", lambda val: re.sub(r"'(\w+?)'", r"\1", val.group()), input))

# 'Siva', [Aswin,latha], 'Senthil',[Aswin,latha]

Comments

1

You can try something like this if you don't want to import re:

X = eval("'Siva', ['Aswin','latha'], 'Senthil',['Aswin','latha']")
Y = []
for x in X:
    Y.append(f"[{', '.join(x)}]" if isinstance(x, list) else f"'{x}'")
print(", ".join(Y))

Comments

1

You can use re.findall with an alternation pattern to find either fragments between ] and [, or otherwise non-single-quote characters, and then join the fragments together with ''.join:

''.join(re.findall(r"[^\]]*\[|\][^\[]*|[^']+", input))

Demo: https://replit.com/@blhsing/ClassicFrostyBookmark

This is generally more efficient than using re.sub with a callback since there is overhead involved in making a callback for each match.

Comments

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.