1. 程式人生 > >PythonCookBook chapter-02-字串

PythonCookBook chapter-02-字串

(python3)

1,利用re模組的split(),字串拆分

import re

str = 'hello world, my name is    leon!'
# \s: 匹配任何空白字元,包括空格、製表符、換頁符等等,等價於 [ \f\n\r\t\v]。
# *: 匹配前面的子表示式零次或多次。
#[]: 字元集合。匹配所包含的任意一個字元
ret = re.split(r'[\s,]\s*', str)
print(ret)

addr = 'www.hao123.com'
# .: 匹配除換行符 \n 之外的任何單字元。要匹配 . ,用 \.
ret = re.split(r'\.', addr)
print(ret)

輸出:

['hello', 'world', 'my', 'name', 'is', 'leon!']
['www', 'hao123', 'com']

捕獲組:點選開啟連結

用到捕獲組,匹配的文字也會包含在結果中;不要捕獲組,以(?:...)指定

2,字串開頭或結尾匹配

>>> filename = 'test.py'
>>> filename.endswith('.py')
True
>>> filename.startswith('te')
True
#正則表示式匹配字串開頭或結尾
>>> import re
>>> re.findall(r'^te', filename)
['te']
>>> re.match(r'^te', filename)
<_sre.SRE_Match object; span=(0, 2), match='te'>
>>> re.match(r'.py$', filename)
>>> re.match(r'*?.py$', filename)
>>> re.search(r'py$', filename)
<_sre.SRE_Match object; span=(5, 7), match='py'>

3,文字模式匹配和查詢

簡單文字匹配可以通過find(), findall(), startswit(),endswith()等函式匹配,複雜匹配可以通過正則表示式進行匹配

# 時間匹配
>>> timepat = re.compile(r'\d{1,2}:\d{1,2}:\d{1,2}')
>>> contents = "Now time is 12:00:00, not 188:18:19"
>>> timepat.findall(contents)['12:00:00']
>>> 
>>> # 網址匹配
>>> address = "www.baidu.com www.edu.cn www.open.org ww.xx"
>>> urlpat = re.compile(r'w{3}\.\w+(?:\.cn|\.com)')
>>> urlpat.findall(address)
['www.baidu.com', 'www.edu.cn']

4,替換,簡單字串可利用replace(),複雜模式可以用sub()或subn(),subn()可以返回替換次數

>>> str = "Hello, leon, this is C world!"
>>> str.replace('C', 'Python')
'Hello, leon, this is Python world!'
>>> str = "I graduated in 2011-07-01."
>>> import re
>>> re.sub(r'(\d{1,4})-(\d{1,2})-(\d{1,2})', r'\3/\2/\1', str)
'I graduated in 01/07/2011.'

5,忽略大小寫可以加引數re.I,正則表示式多行的加引數re.X, 字串是多行的加引數re.M

>>> import re
>>> str = 'python, Python, PyThon'
>>> re.findall('python', str, re.I) #忽略大小寫匹配
['python', 'Python', 'PyThon']
>>> 
>>> 
>>> date = r"""
	\d+
	-
	\d+
	"""
>>> re.findall(date, "Today is 05-10")
[]
>>> re.findall(date, "Today is 05-10", re.X) #正則表示式是多行
['05-10']
>>>
>>>
>>> str ="""
Whateever is
worth doing
is worth
doing well
"""
>>> re.findall(r'worth', str)
['worth', 'worth']
>>> re.findall(r'^worth', str) # ^$這兩個匹配預設只匹配第一行,只有加re.M引數才多行匹配
[]
>>> str
'\nWhateever is\nworth doing\nis worth\ndoing well\n'
>>> re.findall(r'^worth', str, re.M)
['worth']
>>>
>>>
>>> str = """a
b
c"""
>>> re.findall(r'a.b.c', str)
[]
>>> re.findall(r'a.b.c', str, re.S)#re.S會匹配換行符,預設是不匹配換行符的
['a\nb\nc']
>>> 
6, 去掉不需要的字元

去掉兩端字元用strip(),從左或從右去掉字元用lstrip()或rstrip(),去掉所有可以用replace()或re.sub()

其他還可參考點選開啟連結

>>> str = '+++hello world+++'
>>> print(str.strip('+'))
hello world
>>> print(str.lstrip('+'))
hello world+++
>>> print(str.rstrip('+'))
+++hello world
>>> str = '+++hello ++ world+++'
>>> print(str.strip('+'))
hello ++ world
>>> print(str.lstrip('+'))
hello ++ world+++
>>> print(str.rstrip('+'))
+++hello ++ world
>>> print(str.replace('+', ''))
hello  world