hj170520 发表于 2020-5-18 12:44

如何让该题的要输入的正则表达式部分简洁一些

这是一道题目,我的答案见下文
怎么才能更加简洁呢?{:301_999:}
# d) Correct the given RE to get the expected output.

words = 'plink incoming tint winter in caution sentient'
change = re.compile(r'int|in|ion|ing|inco|inter|ink')

# wrong output
change.sub(r'X', words)
# 返回 'plXk XcomXg tX wXer X cautX sentient'
# expected output
change = re.compile('|'.join(sorted(['int','in','ion','ing','inco','inter','ink'], key=len, reverse=True)))    ##### add your solution here
print(change.sub(r'X', words))
# 返回 'plX XmX tX wX X cautX sentient'

哈哈衬 发表于 2020-5-18 13:39

`i(n(|(co)|(ter))?)|(on)`楼主试试!

hj170520 发表于 2020-5-18 13:54

哈哈衬 发表于 2020-5-18 13:39
`i(n(|(co)|(ter))?)|(on)`楼主试试!

返回的结果是:plX XmX tX wXer X cautiX sentient

要求是: 返回 'plX XmX tX wX X cautX sentient'

好像哪里不对{:301_998:}

airdge 发表于 2020-5-18 15:40

re.sub(r'i(n(|(co)|t(?:er)*)*|(on))','X',words)

hj170520 发表于 2020-5-18 16:35

airdge 发表于 2020-5-18 15:40


{:301_1003:}谢谢,太棒了
页: [1]
查看完整版本: 如何让该题的要输入的正则表达式部分简洁一些