【问题标题】:How do I do this regex in Python?如何在 Python 中执行此正则表达式?
【发布时间】:2010-03-09 14:21:35
【问题描述】:

假设我有一个文本字符串,所有字符都是基于拉丁文的。带标点符号。

我如何“找到”所有字符并在其周围放置<strong> 标签?

hay = The fox jumped up the tree.
needle = "umpe"

在这种情况下,“jumped”一词的一部分将被突出显示。

【问题讨论】:

  • 您在编写实际的正则表达式或如何使用pythons regexp 模块时需要帮助吗?
  • 我习惯于在所有东西上使用 .find。我不知道如何将 .replace 与 .find 一起使用。
  • 首先你想替换东西,然后你希望它们不区分大小写。我认为您不知道自己想要什么,或者您的问题不是很清楚。

标签: python regex


【解决方案1】:

没有正则表达式(可能更冗长但也更容易理解):

hay = "The fox jumped up the tree."
needle = "umpe"

print hay.replace(needle, "<strong>%s<strong>" % needle)

在额外规范后编辑:如果您想要不区分大小写的替换(常规字符串替换无法做到这一点):

import re

hay = "The fox jUMPed up the tree."
needle = "umpe"

regex = re.compile('(%s)' % needle, re.I)
print regex.sub('<strong>\\1</strong>', hay)

【讨论】:

  • 如果我想让它不区分大小写怎么办?但是,保留原行的大小写。
  • @alex:此类信息属于问题,不属于 cmets。
【解决方案2】:

在这样的简单搜索表达式上使用正则表达式是多余的。但是,如果您需要更复杂的搜索,我引用了Python's re module documentation 将下面的代码放在一起,我认为它可以满足您的需求:

#!/usr/bin/env python
import re
haystack = "The fox jumped up the tree."
needle = "umpe"
new_text = "<strong>" + needle + "</strong>"
new_haystack = re.sub(needle, new_text, haystack)
print new_haystack

【讨论】:

    【解决方案3】:

    你的问题不是很清楚。如果您想突出显示其中有针的单词,您可以匹配

    \b(\w*needle\w*)\b
    

    替换成

    <strong>\1<strong>
    

    【讨论】:

      【解决方案4】:

      这应该可行:

      pattern = r'(?P<needle>(umpe))'
      pat_obj = re.compile(pattern)
      new_text = pat_obj.sub(r'<strong>\g<needle></strong>', hay)
      

      以 HTML 呈现的结果:狐狸 umpe爬上了树。

      在上面的 sn-p 中,我使用了 re 方法“sub”并引用了一个捕获的组(我称之为“needle”)。

      【讨论】:

        【解决方案5】:

        在这种情况下不使用正则表达式,但适用于较小的字符串。

        hay = "The fox jumped up the tree."
        needle = "umpe"
        
        hay_lower = hey.lower()
        found = []
        curr_find = hay_lower.find(needle.lower())
        found.append(curr_find)
        hay_list = list(hay)
        
        while(curr_find):
            curr_find = hay_lower.find(needle.lower(), curr_find)
        
        for found_index in found:
           hay_list[found_index:found_index+len(needle)] = '<strong>%s</strong>' % needle
        
        result = ''.join(hay_list)
        

        【讨论】:

        • 这不会替换所有匹配项。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2014-11-19
        • 1970-01-01
        • 2021-03-06
        相关资源
        最近更新 更多