How to replace dash between characters with space using regex

后端 未结 4 1155
猫巷女王i
猫巷女王i 2021-01-18 11:56

I want to replace dashes which appear between letters with a space using regex. For example to replace ab-cd with ab cd

The following matc

4条回答
  •  没有蜡笔的小新
    2021-01-18 12:28

    You need to use look-arounds:

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

    Or capturing groups:

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

    See IDEONE demo

    Note that [A-z] also matches some non-letters (namely [, \, ], ^, _, and `), thus, I suggest replacing it with [A-Z] and use a case-insensitive modifier (?i).

    Note that you do not have to escape a hyphen outside a character class.

提交回复
热议问题