Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式将字符之间的破折号替换为空格_Python_Regex - Fatal编程技术网

Python 如何使用正则表达式将字符之间的破折号替换为空格

Python 如何使用正则表达式将字符之间的破折号替换为空格,python,regex,Python,Regex,我想用使用正则表达式的空格替换字母之间出现的破折号。例如,将ab cd替换为ab cd 以下匹配字符序列,但也替换了字符[即,ab cd产生a d,而不是我所希望的ab cd] new_term = re.sub(r"[A-z]\-[A-z]", " ", original_term) 如何调整以上内容以仅替换-部分?使用引用来捕获组: >>> original_term = 'ab-cd' >>> re.sub(r"([A-z])\-([A-z])",

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

以下匹配字符序列,但也替换了字符[即,
ab cd
产生
a d
,而不是我所希望的
ab cd
]

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

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

使用引用来捕获组:

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

当然,这是假设你不能只做
original_term.replace('-','')
,不管出于什么原因。可能您的文本在应该使用破折号的地方使用了连字符。

您需要使用环视:

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

请注意,
[A-z]
还匹配一些非字母(即
[
\
]
^
`
),因此,我建议将其替换为
[A-z]
,并使用不区分大小写的修饰符
(?I)

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

re.sub()
始终使用替换替换替换整个匹配序列

一种只替换破折号的解决方案是前瞻和后顾断言。它们不计入匹配序列

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

new\u term=re.sub(r)(?您需要将
-
之前和之后的字符捕获到一个组中,并使用它们进行替换,即:

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

演示


正则表达式解释

([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»

您不应该使用
[A-z]
,因为正则表达式范围使用ascii表索引。对于此特定范围,您将匹配
A-z[\]^.`A-z
。但是,如果您想使用
A-z
作为不区分键,您可以使用
([A-z])\-([A-z])
。无论如何,我知道OP original regex是这样的……但我只是说。你能用给定字符串中的空格替换
-
吗?是否需要使用regex?@JeffBridgman是的-我只想在字符之间出现破折号时替换,而不是在空格之间替换。也就是说,替换
ab cd
,但不要更改de>ab-cd
-[
replace
没有该控件]。