首页 > 解决方案 > 如何分隔'di'单词中的前缀?

问题描述

我想在单词“di”后面跟字母之后分离一些集成到单词中的前缀。

sentence1 = "dipermudah diperlancar"
sentence2 = "di permudah di perlancar"

我期望这样的输出:

output1 = "di permudah di perlancar"
output2 = "di permudah di perlancar"

演示

标签: pythonregexpython-3.xstringstring-matching

解决方案


这个表达式可能在某种程度上起作用:

(di)(\S+)

如果我们的数据看起来像问题中那样简单。否则,我们会在表达式中添加更多边界。

测试

import re    
regex = r"(di)(\S+)"    
test_str = "dipermudah diperlancar"    
subst = "\\1 \\2"    

print(re.sub(regex, subst, test_str))

该表达式在regex101.com的右上角面板上进行了说明,如果您希望探索/简化/修改它,并且在此链接中,您可以查看它如何与一些示例输入匹配,如果您愿意的话。


推荐阅读