正则表达式删除单词开头、中间以及开头和结尾的连字符

2024-05-15 00:15:31 发布

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

我有一些文档在单词的开头、单词之间以及单词的开头和结尾都有带连字符的文本。 我需要regex的帮助来删除这3个场景中的连字符

示例文本:ease新加坡总部-fis-sgfis-fatca”

我尝试了下面的正则表达式

re.sub(r'[^A-Za-z0-9]+',''“基于新加坡的简易金融机构-新加坡金融机构-fatca”,但它删除了所有催眠


Tags: 文档文本re示例结尾场景字符单词
2条回答

以下是一种方法:

inp = "ease singapore-based -fis -sgfis- fatca"
output = re.sub(r'(?<=\w)-|-(?=\w)', '', inp)
print(output)  # ease singaporebased fis sgfis fatca

上面使用的正则表达式表示要匹配:

(?<=\w)-  match a hyphen preceded by a word character
|         OR
-(?=\w)   match a hyphen followed by a word character

然后,我们用空字符串替换这些匹配的连字符,以删除它们

解决方案1:

re.sub(r'-\b|\b-', ' ', "ease singapore-based fis -sgfis- fatca")
# trim multiple spaces here

表达1:

"-\b|\b-"

\b作为分词线

enter image description here

或 解决方案2

re.sub(r'\s-\b|\b-\s', ' ', "ease singapore-based fis -sgfis- fatca")

表达2:

"\s-\b|\b-\s"

\s从空白字符开始

enter image description here

如果您需要“基于新加坡”成为“基于新加坡”,请使用解决方案2并将其与\b-\b结合使用:

因此,您将以(\b-\b)|(\s-\b|\b-\s)结束

解决方案3:

re.sub(r'(\b-\b)|(\s-\b|\b-\s)', ' ', "ease singapore-based fis -sgfis- fatca")
# no space trimming required

enter image description here

相关问题 更多 >

    热门问题