4.字符串和文本(一)

4.字符串和文本(一)

针对任意多的分隔符拆分字符串

可以使用re.split()来使用多个分隔符来分割字符串

import re
line= 'assd sdfsd; sdfs,sdf,adsdf,    foo'
result=re.split(r'[;,\s]\s*',line)
print(result)

#['assd', 'sdfsd', 'sdfs', 'sdf', 'adsdf', 'foo']

如果要在re.split来使用正则表达式

在字符串的开头或结尾处做文本匹配

可以使用str.startswith()str.endswith()来进行

filename ="test.txt"

print(filename.startswith("test"))
print(filename.endswith(".txt"))
# True
# True

也可以提供多个选项进行,如果要用变量来保存选项,则要只能使用元组结合

filenames = ['siqu.c','siqulab.h','yes.c']

#多个选项要使用元组的方式
result =[filename.endswith(('.c','.h')) for filename in filenames]

print(result)
# [True, True, True]

使用Shell通配符做字符串匹配

函数fnmatch()按照系统底层要求是否忽略大小写

函数fanmatchcase()不忽略大小写

from fnmatch import fnmatch,fnmatchcase
print(fnmatch("foo.txt","*.txt"))
print(fnmatch("foo.txt","?oo.txt"))
print(fnmatch("dat45.csv","dat[0-9][0-9].csv"))

names = ["dat1.csv","dat2.csv","config.ini","foo.py"]
name = [a for a in names if fnmatch(a,"*.csv")]
print(name)

# True
# True
# True
# ['dat1.csv', 'dat2.csv']

文本模式的匹配和查找

使用正则表达式进行匹配

import re

if re.match(r'\d+/\d+/\d+',"11/27/2012"):
    print("yes")
else:
    print("no")
# yes
import re

#匹配单个
if re.match(r'\d+/\d+/\d+',"11/27/2012"):
    print("yes")
else:
    print("no")

#匹配全部结果
text = "today is 11/27/2012.pycon starts 3/13/2013"
detepat=re.compile(r'\d+/\d+/\d+')
print(detepat.findall(text))

#可以使用finditer()返回迭代结果
text = "today is 11/27/2012.pycon starts 3/13/2013.cs 12/2/2011"
for i in detepat.finditer(text):
    if i:
        print("yes",end=" ")

# yes
# ['11/27/2012', '3/13/2013']
# yes yes yes

查找和替换文本

import re

#普通替换
text = 'yeah,but no,but yeah,but no,but yeah'
text=text.replace('yeah','yep')
print(text)

#正则表达式替换
text2 = 'today is 11/27/2012'
text2=re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2',text2)
print(text2)

#创建正则表达式对象
text3 = 'yestoday is 11/26/2012'
match = re.compile(r'(\d+)/(\d+)/(\d+)')
text3=match.sub(r'\3-\1-\2',text3)
print(text3)

# yep,but no,but yep,but no,but yep
# today is 2012-11-27
# yestoday is 2012-11-26

以不区分大小写的方式对文本做查找和替换

可以使用re模块的re.IGNORECASE标记

import re
text = 'UPPER PYTHON,lower python,Mixed Python'

print(re.findall('python',text,flags=re.IGNORECASE))
print(re.sub('python','snake',text,flags=re.IGNORECASE))

# ['PYTHON', 'python', 'Python']
# UPPER snake,lower snake,Mixed snake

待替换的文本与匹配的文本大小写并不匹配,可以使用一个支持函数

import re

#使用支撑函数
def matchcase(word):
    def replace(m):
        text = m.group()
        if text.isupper():
            return word.upper()
        elif text.islower():
            return word.lower()
        elif text[0].isupper():
            return word.capitalize()
        else:
            return word
    return replace

text = 'UPPER PYTHON,lower python,Mixed Python'
print(re.sub('python',matchcase('snake'),text,flags=re.IGNORECASE))

# UPPER SNAKE,lower snake,Mixed Snake

定义实现最短匹配的正则表达式

import re
str_pat = re.compile(r'\"(.*)\"')
text2 = 'Computer says "no." Phone says "yes."'

#错误匹配
print(str_pat.findall(text2))

#强制匹配最短结果,在*或+后添加一个?
str_pat = re.compile(r'\"(.*?)\"')
print(str_pat.findall(text2))

# ['no." Phone says "yes.']
# ['no.', 'yes.']

编写多行模式的正则表达式

需要对正则表达式中添加对回车符的支持

还可以使用正则表达式标记re.DOTALL,那么就可以使得.能够匹配所有字符

import re
text1 = '''/* this is a
      multiline comment */'''

dat=re.compile(r'/\*((?:.|\n)*?)\*/')
print(dat.findall(text1))

# [' this is a\n      multiline comment ']

#使用标记来进行匹配
dat=re.compile(r'/\*(.*?)\*/',re.DOTALL)
print(dat.findall(text1))

# [' this is a\n      multiline comment ']
# [' this is a\n      multiline comment ']

将Unicode文本统一表示为规范格式

可以使用unicodedata模块来完成

#noemalize的第一个参数指定了字符串应该如何完成规范表示

t1 = unicodedata.normalize("NFC",s1)
© 版权声明
THE END
喜欢就支持以下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容