加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式

发布时间:2020-12-13 22:09:12 所属栏目:百科 来源:网络整理
导读:Python 中对字符串匹配可能会用到 str.startswith(str,beg=0,end=len(string)); str.endswith(suffix[,start[,end]]); str.find() 在(文件中)一行中使用 endwith 方法的时候注意 ‘n’ ——换行标识,当然对每一行使用了 rstrip() 方法的话就不用在关键字后

Python 中对字符串匹配可能会用到

str.startswith(str,beg=0,end=len(string));

str.endswith(suffix[,start[,end]]);

str.find()

在(文件中)一行中使用 endwith 方法的时候注意 ‘n’ ——换行标识,当然对每一行使用了 rstrip() 方法的话就不用在关键字后面加 ‘n’ 了。

def findKey(fname):
    file = open(fname)
    for line in file:
        if line.startswith('xx') 
                or line.endswith('xxn'): # or line[:-1].endswith('xx'):
            print line

    file = open(fname)
    for line in file:
        line = line.rstrip()
        if line.startswith('xx') or line.endswith('xx'):
            print line

findKey('test.txt')
匹配字母或者下划线开头的字符串
#a = ''
a = '_value'
# a can not be null or useless,'a and' put 1th
boolean = a and ( a[0]== '_' or 'a' <= a[0] <= 'z')
print boolean


Python正则表达式需要re模块

import re
str = 'Xnxx python'
#<a target=_blank href="http://blog.csdn.net/no_enemy/article/details/46609927#t1"> use 'r' can match exactlly what you write</a> 参考第六
#regular = re.compile('xn',re.I)
regular = re.compile(r'xn',re.I) #build one object,re.I,ignore lower or uppercase,add 'r' is better
#print regular,type(regular)
result = regular.match(str)  #return a object to store match result.
#print regular.match(str)
if result == None:
    print 'Nothing find'
else:
    print result.span() #check index
# use once
result = re.match(r'x',str) # str is target string
上述代码中的 match() 方法是从0开始匹配,如果0位没有,则没有匹配失败,匹配失败之后如果打印 result 你会发现 result 是None,可以使用这个值进行判定


正则表达式入门语法

匹配单个字符

1. 匹配以a开头,z 结尾的三个字母构成的字符串
result = re.match(r'a.z','a8z')
print result.span()
—— . 小数点:匹配除了换行符(n)以外的任意一个字符,一个字符,一个
所以下列代码是匹配失败的
result = re.match(r'a.z','anz')
result = re.match(r'a.z','axxz')

2. 匹配以字母或者数字开头的字符串
result = re.match(r'[a-zA-Z0-9]','hello')
print result.group()
—— [] 方括号:能够匹配方括号内任意一个字符
上述问题解决方法二:
result = re.match(r'[w]','hello')
print result.group()
——w:表示任意一个字母或数字或下划线,也就是 A~Z,a~z,0~9,_ 中任意一个

3. 匹配以括号[]内有任意一个字母或数字或下划线开头的字符串
result = re.match(r'[[w]]','[0]891') # if you want to find a str including [],you should use 
print result.group()

匹配多个字符

1. 匹配任意多个字符或者数字或下划线开头的字符串
result = re.match(r'[w]*','dsuio28A$$$$')
print result.group()
——* 星号:匹配前一个规则 0~n 次

2. 匹配一个有效的 Python 变量(以下划线字母开头,所以必须存在1次或以上)
result = re.match(r'[_a-zA-Z]+[_w]*','_python')
print result.group()

3. 匹配 0- 99 的数字
第一反应可能会是:
result = re.match(r'[0-99]','99')
print result.group()
发现结果其实只能匹配第一个数字,因为用的是上面的匹配一个字符,那么这里的 0 - 99 要匹配多个字符,也有可能是一个字符
result = re.match(r'[0-9]?[0-9]','55')
print result.group()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读