【问题标题】:How to replace dash between characters with space using regex如何使用正则表达式用空格替换字符之间的破折号
【发布时间】:2015-10-13 21:57:03
【问题描述】:

我想使用正则表达式将出现在字母之间的破折号替换为空格。例如用ab cd替换ab-cd

以下匹配字符-字符序列,但也替换字符 [i.e. ab-cd 结果是 a d,而不是我想要的 ab cd]

 new_term = re.sub(r"[A-z]\-[A-z]", " ", original_term)

我如何调整上述内容以仅替换 - 部分?

【问题讨论】:

  • 您可以通过简单地将- 替换为给定字符串中的空格来做到这一点吗?有必要使用正则表达式吗?
  • @JeffBridgman 是的 - 我只想在字符之间出现破折号时替换,而不是在空格之间时替换。即替换ab-cd,但不更改ab - cd - [replace 没有该控制]。

标签: python regex


【解决方案1】:

您需要将-beforeafter 字符捕获到一个组中,并将它们用于替换,即:

import re
subject = "ab-cd"
subject = re.sub(r"([a-z])\-([a-z])", r"\1 \2", subject , 0, re.IGNORECASE)
print subject
#ab cd

演示

http://ideone.com/LAYQWT


正则表达式解释

([A-z])\-([A-z])

Match the regex below and capture its match into backreference number 1 «([A-z])»
   Match a single character in the range between “A” and “z” «[A-z]»
Match the character “-” literally «\-»
Match the regex below and capture its match into backreference number 2 «([A-z])»
   Match a single character in the range between “A” and “z” «[A-z]»

\1 \2

Insert the text that was last matched by capturing group number 1 «\1»
Insert the character “ ” literally « »
Insert the text that was last matched by capturing group number 2 «\2»

【讨论】:

    【解决方案2】:

    使用对捕获组的引用:

    >>> original_term = 'ab-cd'
    >>> re.sub(r"([A-z])\-([A-z])", r"\1 \2", original_term)
    'ab cd'
    

    当然,这假设您不能出于任何原因只做original_term.replace('-', ' ')。也许您的文本在应该使用破折号或其他内容的地方使用连字符。

    【讨论】:

    • 您不应该使用[A-z],因为正则表达式范围使用 ascii 表索引。对于此特定范围,您将匹配 A-Z[\]^_`a-z。但是,如果您想使用 a-z 作为键不敏感,您可以使用 (?i)。例如,您可以拥有(?i)([a-z])\-([a-z])。无论如何,我知道 OP 原始的正则表达式就是……但只是说。
    【解决方案3】:

    re.sub() 总是用替换替换整个匹配序列。

    仅替换破折号的解决方案是 lookaheadlookbehind 断言。它们不计入匹配的序列。

    new_term = re.sub(r"(?<=[A-z])\-(?=[A-z])", " ", original_term)
    

    语法在Python documentation for the re module中解释。

    【讨论】:

      【解决方案4】:

      您需要使用环视:

       new_term = re.sub(r"(?<=[A-Za-z])-(?=[A-Za-z])", " ", original_term)
      

      或捕获组:

       new_term = re.sub(r"([A-Za-z])-(?=[A-Za-z])", r"\1 ", original_term)
      

      IDEONE demo

      注意[A-z]也匹配一些非字母(即[\]^_`),因此,我建议用@替换它987654331@ 并使用不区分大小写的修饰符(?i)

      请注意,您不必在字符类之外转义连字符。

      【讨论】:

        【解决方案5】:

        我知道这是一个老话题,但我认为有一种简单的方法可以在多行文本框中使用 Visual basic 替换破折号:

        Regex.Replace(ReadText.Text, "[-]", "")

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-19
          相关资源
          最近更新 更多