简体   繁体   English

在Python中搜索并替换字符串中的一些文本?

[英]Search and replace some text in strings in Python?

I would like to search in a text of multiple lines to see if each line has sentence=" followed by some text and ended with " />' . 我想搜索多行的文本,看看每行是否有sentence="后跟一些文字,以" />'结尾。 If yes, see if the text between sentence=" and " />' has " , if yes, replace it with ' . For example, one such line is: 如果是,请查看sentence="" />'之间的文本是否具有" ,如果是,则将其替换为' 。例如,一条这样的行是:

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

I would like to change it to be 我想改变它

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

Note that such cases can happen more than once in each single line of the text. 请注意,此类情况可能会在文本的每一行中出现多次。

I wonder how to use regex in Python to accomplish that? 我想知道如何在Python中使用正则表达式来实现这一目标? Thanks! 谢谢!

You can provide a callable to re.sub to tell it what to replace the match object with: 您可以为re.sub提供一个callable来告诉它用以下内容替换匹配对象:

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!\'" />'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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