【问题标题】:Python: Replacing strings [duplicate]Python:替换字符串[重复]
【发布时间】:2013-09-10 02:24:29
【问题描述】:

我正在遍历页面,我想修改包含

的行
<span class="font16"></span>

如何更正下面的代码?

text = re.sub(r'<span class="font(.*)"></span><span', r'<span class="font\1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span><span', text)

【问题讨论】:

  • 你有什么问题?
  • 马上,我可以指出(.*) 是贪婪的,并且会尽可能地走到最后,然后离开&gt;&lt;/span&gt;&lt;span,这很可能会消耗更多的东西.
  • 请查看该问题投票最多的答案:stackoverflow.com/questions/1732348/…
  • .* 更改为[^"]*
  • 您可以简单地使用r'&lt;span class="font\1"&gt;{} &lt;/span&gt;&lt;span'.format(' '.join(["&amp;nbsp;"] * N)) 代替"&lt;span class="font\1"&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; ..." 类型的字符串文字,其中N 是您要插入该字符串的次数。

标签: python html regex


【解决方案1】:

模式.* 将匹配任何内容,直到行尾,所以匹配看起来像这样:

16"></span>....

这不是你想要的。使用在第一个 " 处停止的模式(因为它们不允许在用 " 引用的属性值内):

r'<span class="font([^"]+)"></span><span'

【讨论】:

  • 好的,现在,我知道了: text = re.sub(r'{} ; 我想在 font16"> 和 之间插入符号。
  • 我想知道为什么跨度是空的。您可能应该搜索 &lt;span class="font([^"]+)"&gt; 而没有关闭 &lt;/span&gt; 或下一个跨度..
猜你喜欢
  • 2016-06-06
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
相关资源
最近更新 更多