简体   繁体   中英

Finding a single quote after an equal sign in a string using regex python

I have a list of strings formatted as follows:

value="hello"

The issue is that in some cases, there is no double quote after the equal sign (it may be a single quote or no quotes at all).

I am trying to add the double quote into the string.

I have tried the follow regex python code at regex101.com using the python mode:

import re

string1="value='hello''"
string1=string1.replace("''",'"')

regex = r'=[^\"]'

subst = '=\"'

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, string1, 0, re.MULTILINE)

print(result)

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

I am expecting the result to print out as

"hello"

but I am getting

'hello"

You can use a pattern that looks for a word surrounded in optional single quotes, and substitute it with the word in double quotes:

print(re.sub(r"(?<==)'*(\w+)'*", r'"\1"', "value='hello''"))
print(re.sub(r"(?<==)'*(\w+)'*", r'"\1"', "value=hello"))

This outputs:

value="hello"
value="hello"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM