首页 > 解决方案 > 在字符串中的特定模式内替换 | 正则表达式

问题描述

我希望'/'在以特定模式(前面和后面跟一个字符)发生时用"".

例子

  1. "a/b b/c"应更换为 "ab bc"

  2. "a/b python/Java"应更换为 "ab python/Java"

虽然,我知道如何使用 regex 进行替换re.sub("/","","a/b python"),但问题是,替换只需要在字符串的特定部分进行。

这里的任何帮助将不胜感激。谢谢

标签: pythonregexpython-3.x

解决方案


这简化并扩展了Code Maniac 的评论:

您可以使用re.sub替换找到的模式

import re

regex = r"(\b\w)\/(\w\b)" # do not capture the /

test_str = """a/b b/c
a/b python/Java"""

subst = r"\1\2"           # replace with 1st and 2nd capture group
result = re.sub(regex, subst, test_str, flags=re.MULTILINE)

if result:
    print (result)

作为模式r"(\b\w)\/(\w\b)",您定义了一个单词边界 + 1 个单词字符,\然后是 1 个单词字符,然后是一个单词边界。您将其捕获为 1. 和 2. 组 -\ 未捕获。

您将每个匹配项替换为 before/after 捕获的组/

输出:

ab bc
ab python/Java

测试:https ://regex101.com/r/WI0Wg3/1


推荐阅读