如何替换子字符串,但仅当它恰好出现在两个单词之间时

时间:2019-06-20 11:10:32

标签: python regex substring

在python中,我需要将" - "替换为"-",但前提是两个词之间出现[SPACE][DASH][SPACE]

[SPACE][SPACE][DASH][SPACE][SPACE]不会更改。即:

" - The quick - brown fox jumps - over the -"必须更改为

" - The quick-brown fox jumps - over the -"

This is jumps[SPACE][SPACE][DASH][SPACE][SPACE] ...

我不能把头放在正则表达式上。

2 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式搜索单词边界:

\b - \b

RegEx Demo

由于两侧的单词边界,仅当两侧的单词字符包围空格时,它才会匹配。

代码:

import re

test_str = " - The quick - brown fox jumps  -  over the -"


# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(r"\b - \b", '-', test_str)

if result:
    print (result)

答案 1 :(得分:0)

在@anubhavva的帮助下,我构建了此通用功能:

def replace_in_word(replace_in, replace_what, replace_with):
    #in string replace_in, replace_what with replace_with, and return the string
    #but only inside a word
    #if not found, return unchanged string
    return(re.sub(r"\b%s\b" % replace_what, replace_with, replace_in))