【问题标题】:How to find and replace the whole word (exact match) from a string in python using "re" package while the string contains the metacharacter?如何在字符串包含元字符时使用“re”包从python中的字符串中查找和替换整个单词(完全匹配)?
【发布时间】:2020-05-10 03:46:20
【问题描述】:

例如,

line = "array[0] is the first element, array[0]some_character, is not a valid element"

我只想在字符串中查找并替换"array[0]"。在这种情况下,假设我想用单词"element1" 替换它。那么输出应该如下:

line = "element1 is the first element, array[0]some_character, is not a valid element".

请注意,在字符串中,array[0]some_character 应该保持不变,而不应该像"element1some_character" 那样被替换

感谢任何人的帮助。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    尝试关注

    word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
    re.sub(r'ab\[0\](\s|$)', r'ahmed\1', word)
    

    输出:

    'abcd ab[0]c ahmed class ab[0]d classified ahmed'

    或使用前瞻

    word = "abcd ab[0]c ab[0] class ab[0]d classified ab[0]"
    re.sub(r'ab\[0\](?=\s|$)', r'ahmed', word)
    

    输出:

    'abcd ab[0]c ahmed class ab[0]d classified ahmed'

    【讨论】:

    • 嗨,它可以工作,但它有一个小问题。如果字符串类似于 word = "abcd ab[0]c ab[0], class ab[0]d 分类 ab[0]":逗号是紧跟在 ab[0] 之后的位置,那么它不考虑 ab[ 0] 一个完整的词。
    【解决方案2】:

    t = "array[0] is the first element, array[0]some_character, is not a valid element" re.sub("a[a-z]+\[[0-9]+\](?=[\s]{1})", "Element1", t)

    您在正则表达式的末尾看到 - (?=[\s]{1}),第二个数组 [0] 后面没有空格,因此不会被替换。

    【讨论】:

      【解决方案3】:
      import re
      
      line = "array[0] is the first element, second is array[0], array[0]some_character, is not valid element array[0]."
      res = re.sub(r'\barray\[0\](?!\w)', 'REPL', line)
      print res
      

      输出:

      REPL is the first element, second is REPL, array[0]some_character, is not valid element REPL.
      

      说明:

      \b              # word boundary, to not match isarray[0]
      array\[0\]      # the string to match
      (?!\w)          # negative lookahead, make sure we haven't a word character after
      

      Demo & explanation

      【讨论】:

      【解决方案4】:
      import re
      
      line = "array[0] is the first element, array[0]some_character, is not a valid element"
      re.sub('array\[0\]\s','element1 ',line)
      

      输出: 'element1 是第一个元素,array[0]some_character,不是有效元素'

      【讨论】:

      • 欢迎来到 Stack Overflow!虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 2017-05-26
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多