如何使用正则表达式用空格替换字符之间的破折号 [英] How to replace dash between characters with space using regex

查看:47
本文介绍了如何使用正则表达式用空格替换字符之间的破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

The following matches the character-character sequence, however also replaces the characters [i.e. ab-cd results in a d, rather than ab cd as i desire]

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

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

How i adapt the above to only replace the - part?

推荐答案

您需要捕获 - 中的 beforeafter 字符以一组并使用它们进行替换,即:

You need to capture the characters before and after the - to a group and use them for replacement, i.e.:

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»

这篇关于如何使用正则表达式用空格替换字符之间的破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆