錨定
錨定碼 |
含義 |
^ |
字符串或行的開始 |
$ |
字符串或行的結(jié)束 |
\A |
字符串開始 |
\Z |
字符串結(jié)束 |
\b |
一個單詞開頭或末尾的空串 |
\B |
不在一個單詞開頭或末尾的空串 |
匹配字符串的第一個單詞(或字母)
# 匹配字符串的第一個單詞(或字母)
# ^ 表示字符串或行的開始蛤奢,w+表示字母和數(shù)字
import re
# 文本
text = 'hello h123 abc123'
# 匹配規(guī)則
pattern = r'\bh\w*'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['hello', 'h123']
<_sre.SRE_Match object; span=(0, 5), match='hello'>
<_sre.SRE_Match object; span=(6, 10), match='h123'>
# 匹配字符串的第一個單詞(或字母)
# \A表示字符串的開始,w+表示字母和數(shù)字
import re
# 文本
text = 'hello world 123abc'
# 匹配規(guī)則
pattern = r'\A\w+'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['hello']
<_sre.SRE_Match object; span=(0, 5), match='hello'>
匹配字符串最后一個單詞
# 匹配字符串最后一個單詞,跳過標(biāo)點符號
# \w+ 表示1個或多個字母和數(shù)字
# \S* 表示0個或多個非空白符
# $ 表示字符串或行的結(jié)束
import re
# 文本
text = 'hello world 123abc'
# 匹配規(guī)則
pattern = r'\w+\S*$'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['123abc']
<_sre.SRE_Match object; span=(12, 18), match='123abc'>
# 匹配字符串最后一個單詞所宰,跳過標(biāo)點符號
# \Z 表示字符串或行的結(jié)束
import re
# 文本
text = 'hello world 123abc'
# 匹配規(guī)則
pattern = r'\w+\S*\Z'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['123abc']
<_sre.SRE_Match object; span=(12, 18), match='123abc'>
匹配包含某字母
# 匹配包含字母'o'的單詞
import re
# 文本
text = 'hello world oct 123abc'
# 匹配規(guī)則
pattern = r'\w*o\w*'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['hello', 'world', 'oct']
<_sre.SRE_Match object; span=(0, 5), match='hello'>
<_sre.SRE_Match object; span=(6, 11), match='world'>
<_sre.SRE_Match object; span=(12, 15), match='oct'>
匹配某字母開頭的單詞
# 匹配字母'h'開頭的單詞
import re
# 文本
text = 'hello shanghai 123abc'
# 匹配規(guī)則
pattern = r'\bh\w*'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['hello']
<_sre.SRE_Match object; span=(0, 5), match='hello'>
匹配某字母結(jié)尾的單詞
# 匹配結(jié)尾為字母'o'的單詞
import re
# 文本
text = 'hello our world'
# 匹配規(guī)則
pattern = r'\bh\w*'
print(re.findall(pattern,text))
for i in re.finditer(pattern,text):
print(i)
>>>
['hello']
<_sre.SRE_Match object; span=(0, 5), match='hello'>