Finding and replacing any text in strings in Python?

I would like to search several lines in the text to see if each line has sentence="some text and ends with " />'. If yes, see if there is text between sentence="and " />' ", if so, replace it with '. For example, one such line:

<number="4" word="start" sentence="I said, "start!"" />

I would like to change it as

<number="4" word="start" sentence="I said, 'start!'" />

Please note that such cases may occur more than once in each separate line of text.

I wonder how to use regex in Python for this? Thank!

+4
source share
1 answer

You can specify the callee re.subto tell you to replace the matching object:

s = """<number="4" word="start" sentence="I said, "start!"" />"""

re.sub(r'(?<=sentence=")(.*)(?=" />)', lambda m: m.group().replace('"',"'"), s)
Out[179]: '<number="4" word="start" sentence="I said, \'start!\'" />'
+3
source

Source: https://habr.com/ru/post/1532231/


All Articles