如何替换子字符串,但前提是它正好出现在两个单词之间

2024-09-28 13:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在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] ...

我不能把我的头缠在正则表达式上


Tags: theisspacequickthis单词overdash
2条回答

在@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))

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

\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)

相关问题 更多 >

    热门问题