python regex

#python

1.check valid

import re

def main():
    username = input('please input username:')
    qq = input('please input qq:')

    m1 = re.match(r'^[0-9a-zA-Z_]{6,20}$', username)
    if not m1:
        print('please input valid username')

    m2 = re.match(r'^[1-9]\d{4,11}$', qq)
    if not m2:
        print('please input valid qq')

    if m1 and m2:
        print('input is valid')

if __name__ == '__main__':
    main()

2. find phone number

import re


def main():
    pattern = re.compile(r'(?<=\D)1[34578]\d{9}(?=\D)')
    sentence = 'my phone is 13056248933 not 15625486587.'

    # find all
    mylist = re.findall(pattern, sentence)
    print(mylist)

    print('----------------')
    # find by iterate
    for temp in pattern.finditer(sentence):
        print(temp.group())

    print('----------------')
    # find by search
    m = pattern.search(sentence)
    while m:
        print(m.group())
        m = pattern.search(sentence, m.end())


if __name__ == '__main__':
    main()

3.replace dirty words

import re


def main():
    sentence = 'fuck you, thank you'
    purified = re.sub('fuck|shit', '*', sentence, flags=re.IGNORECASE)
    print(purified)


if __name__ == '__main__':
    main()

4.split sentence

import re


def main():
    poem = 'Hello, my name is xxx. nice to need you'
    sentence_list = re.split(r'[,。, .]', poem)
    while '' in sentence_list:
        sentence_list.remove('')
    print(sentence_list)


if __name__ == '__main__':
    main()
符号解释示例说明
.匹配任意字符b.t可以匹配bat / but / b#t / b1t等
\w匹配字母/数字/下划线b\wt可以匹配bat / b1t / b_t等
但不能匹配b#t
\s匹配空白字符(包括\r、\n、\t等)love\syou可以匹配love you
\d匹配数字\d\d可以匹配01 / 23 / 99等
\b匹配单词的边界\bThe\b
^匹配字符串的开始^The可以匹配The开头的字符串
$匹配字符串的结束.exe$可以匹配.exe结尾的字符串
\W匹配非字母/数字/下划线b\Wt可以匹配b#t / b@t等
但不能匹配but / b1t / b_t等
\S匹配非空白字符love\Syou可以匹配love#you等
但不能匹配love you
\D匹配非数字\d\D可以匹配9a / 3# / 0F等
\B匹配非单词边界\Bio\B
[]匹配来自字符集的任意单一字符[aeiou]可以匹配任一元音字母字符
[^]匹配不在字符集中的任意单一字符[^aeiou]可以匹配任一非元音字母字符
*匹配0次或多次\w*
+匹配1次或多次\w+
?匹配0次或1次\w?
{N}匹配N次\w{3}
{M,}匹配至少M次\w{3,}
{M,N}匹配至少M次至多N次\w{3,6}
|分支foo|bar可以匹配foo或者bar
(?#)注释
(exp)匹配exp并捕获到自动命名的组中
(? <name>exp)匹配exp并捕获到名为name的组中
(?:exp)匹配exp但是不捕获匹配的文本
(?=exp)匹配exp前面的位置\b\w+(?=ing)可以匹配I’m dancing中的danc
(?<=exp)匹配exp后面的位置(?<=\bdanc)\w+\b可以匹配I love dancing and reading中的第一个ing
(?!exp)匹配后面不是exp的位置
(?<!exp)匹配前面不是exp的位置
*?重复任意次,但尽可能少重复a.*b
a.*?b
将正则表达式应用于aabab,前者会匹配整个字符串aabab,后者会匹配aab和ab两个字符串
+?重复1次或多次,但尽可能少重复
??重复0次或1次,但尽可能少重复
{M,N}?重复M到N次,但尽可能少重复
{M,}?重复M次以上,但尽可能少重复
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐