First, the regular expression:
Regular expressions not used in python, but is available in all languages. Just call the method varies.
#在python中纯代码校验手机号码:
while True: phone_number = input('please input your phone number :') if len(phone_number) == 11 \ and phone_number.isdigit()\ and (phone_number.startswith('13') \ or phone_number.startswith('14') \ or phone_number.startswith('15') \ or phone_number.startswith('16')\ or phone_number.startswith ( ' 17 ' ) \ or phone_number.startswith ( ' 18 ' )): Print ( ' legitimate phone number ' ) the else : Print ( ' is not a valid phone number ' )
# Re calls in python modules use regular expressions to check the phone number:
Import Re PHONE_NUMBER = INPUT ( ' Please INPUT your Phone Number: ' ) IF re.match ( ' ^ (13 is | 14 | 15 | 16 |. 17 | 18 is) [0-9]. 9} {$ ' , PHONE_NUMBER): Print ( ' a legitimate phone number ' ) the else : Print ( ' is not a valid phone number ' )
Conclusion: The call re module in python using regular expressions will be simple lot.
Regular expression syntax is as follows:
Which quantifier '*', '+', '? 'Are greedy matching is to match the character more times, if a quantifier behind the increase'? 'This symbol, it means an inert match, in other words to try to match less.
Embodied in matching real column as follows:
1. '.', '^', '$' Three specific performance
2.'? ',' + ',' * ',' {} 'Embodied
When coupled with the quantifier '? 'Changed.
3 '[^] *' usage:
Second, the combination of several conventional greedy summary matches
Third, greedy matching and non-matching greedy
1.
re模块的使用:
三个必须掌握的方法有如下
1.findall
import re res = re.findall('c','andy cody jcason') #查找字符串中所有‘c’字符 print(res)#返回所有的满足匹配条件的放在列表里, ['c','c']
findall 查找所有字符,只要是能匹配到的字符,全部放在一个列表里,不需要调用group方法。
2.search
import re
res = re.search('c','ancdy cody jcason') print(res.group()) #用group方法
search 查找所有字符,只要找到第一个匹配到的字符后会停止查找,并返回匹配的字符。
全部字符中如果没有要找的字符,就会返回None,如果用group方法调用就会报错。
3.match
import re
res = re.match('c','cncdy cody jcason')
print(res.group()) #‘c’
match 只会找字符中的开头字符是否含有所匹配的字符,有就会返回匹配的字符
如果字符开头不是要找的字符,就会返回None, 如果用group方法调用就会报错
其他涉及到的使用方法:
1.split
ret = re.split('[ab]', 'abcd') # 先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割 print(ret) # ['', '', 'cd']
2.sub
ret = re.sub('\d', 'W', '3andy4cody4', 1) # 将数字替换成'W',参数1表示只替换1个 print(ret) # Wandy4cody4
3.subn
ret = re.subn('\d', 'W', '3andy4cody4', 1) # 将数字替换成'W' print(ret) # WandyWcodyW 返回元组(替换的结果,替换了多少次)
4.compile
obj = re.compile('\d{3}') #将正则表达式编译成为一个 正则表达式对象,规则要匹配的是3个数字 ret = obj.search('abc123eeee') #正则表达式对象调用search,参数为待匹配的字符串 print(ret.group()) #结果 : 123