使用字符串方法find()时丢弃特定的字符序列

时间:2017-03-29 14:51:18

标签: python regex string find

有没有办法在Python 3 +中实现这个目标?

我有一个字符串He said: <p>He<i>ll</i>o how are you?,它将这些HTML标记包含为纯文本。方法find()返回带有搜索字符串的索引(位置)。是否有find()的任何正则表达式版本,我可以输入此<[^<]+?>作为正则表达式来查找&lt; &GT; (或者可能是它的负向前瞻) - 所以忽略它们来寻找单词Hello但仍然在原始字符串中获得绝对位置?

例如:

String = He said: <p>He<i>ll</i>o how are you?

功能可以是foo(String, "<[^<]+?>", "Hello")

中的foo(search in this string, exclude characters matching this regex, look for this

..并获得13作为原始字符串中Hello字的位置作为回报?

1 个答案:

答案 0 :(得分:0)

re.search('(?:<[^<]+?>)*'.join('Hello'), 'He said: <p>He<i>ll</i>o how are you?').start()返回12(第13个字符)。

如果您不确定Hello是否在字符串中,则应在调用search之前检查None是否返回start

相关问题