替换字符串中的特定模式|正则表达式

时间:2018-12-30 16:07:27

标签: python regex python-3.x

当以某种特定样式(在字符之前和之后)出现时,我希望将字符'/'替换为""

示例

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

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

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

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

2 个答案:

答案 0 :(得分:2)

这简化并扩展了Code Maniac's条评论:

您可以使用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.组-\  没有被捕获。

您用/之前/之后的捕获组替换每个匹配项。

输出:

ab bc
ab python/Java

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

答案 1 :(得分:1)

您可能要做的是首先将模式与1个以上的字符(/,双引号之间的1个以上的字符)匹配。然后,因为模式匹配,您可以分割字符串并检查item的字符串长度是否为3。

如果是,请使用map并将/替换为空字符串并重建该字符串。

匹配完整模式:

"\w+\/\w+(?: \w+\/\w+)*"

Regex demo | Python demo

例如:

import re

regex = r"\"\w+\/\w+(?: \w+\/\w+)*\""
test_str = ("\"a/b b/c\"\n"
    "\"a/b python/Java\"")
matches = re.findall(regex, test_str, re.MULTILINE)

for match in matches:
    res = map(lambda s: s.replace("/", "") if len(s) == 3 else s, match.strip("\"").split())
    print('"{0}"'.format(" ".join(res)))

结果

"ab bc"
"ab python/Java"