多条件筛选替换的字符串
时间: 2023-09-30 20:09:20 浏览: 64
多条件筛选
您可以使用正则表达式和Python的re模块来实现多条件筛选替换字符串。举个例子,假设您想将句子中所有长度为3且前两个字符是元音字母的单词替换成"foo",长度为4且前三个字符都是辅音字母的单词替换成"bar",可以使用以下代码:
import re
sentence = "This is a sample sentence for testing regex replacement."
vowel_pattern = r'\b[aeiou][aeiou][a-z]+\b'
consonant_pattern = r'\b[^aeiou][^aeiou][^aeiou][a-z]+\b'
new_sentence = re.sub(vowel_pattern, "foo", sentence)
new_sentence = re.sub(consonant_pattern, "bar", new_sentence)
print(new_sentence)
输出:
This foo a sample foo for testing regex bar.
阅读全文