练习测试网站:https://regexr.com/
正则表达式进阶练习:https://alf.nu/RegexGolf
答案参考:https://blog.csdn.net/NJYR21/article/details/79600217
. :匹配除换行符以外所有字符
\d{2}:匹配指定长度的数字
\d{2,4}:贪婪匹配2-4
d也你可以为w等
abd?:匹配其中ab/abd等(d出现0次或一次)
abc*:匹配c 0次或无限次
abc+ : 匹配c 至少一次
a(bc)+ : 匹配bc 至少一次
[acd]:指定需要的字符,a,c,d每个都会查找匹配
(…).*\1:匹配所有类似abc***abc类的字符(前变匹配的三个出现后边也出现)

^(?!.(.)(.)\2\1):匹配所有非abba类型的字符串
^(.)(.).
\2\1$:匹配所有回文

sub函数可用来进行替换
subn完成替换后可返回替换词数

正则表达式练习

练习1

def clean_email_text(text):
    text = text.replace('\n',' ')           #去掉换行符
    text = re.sub("-"," ",text)             #用空格替换掉‘-’
    text = re.sub(r"\d+/\d+/\d+"," " ,text)  #去掉日期数据
    text = re.sub(r"[0-2]?[0-9]:[0-6][0-9]", "", text)  # 时间,没意义
    text = re.sub(r"[\w][email protected][\.\w]+", "", text)  # 邮件地址,没意义
    text = re.sub(r"/[a-zA-Z]*[:\//\]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i", "", text)  # 网址,没意义
    pure_text = ''
    # 以防还有其他特殊字符(数字)等等,我们直接把他们loop一遍,过滤掉
    for letter in text:
        # 只留下字母和空格
        if letter.isalpha() or letter == ' ':
            pure_text += letter
    # 再把那些去除特殊字符后落单的单词,直接排除。
    # 我们就只剩下有意义的单词了。
    text = ' '.join(word for word in pure_text.split() if len(word) > 1)
    return text

练习2

#定义降噪函数
def removeNoise(document):
    noise_patten = re.compile('|'.join(['http\S+','\@\w+','\#\w+']))
    clean_text = re.sub(noise_patten,'',document)
    return clean_text.strip()

print(removeNoise("Trump images are now more popular than cat gifs. @trump trends http://www.trumptrends.html"))

输出:
Trump images are now more popular than cat gifs.

相关文章: