在我们日常使用中,经常需要搜索关键位置进行字符串的匹配,比如一行文本的开头,又比如一个字符串的开头,或者结尾。 这时候就需要使用正则表达式的边界符进行匹配,它们定义如下:
定义字符
意义
^
字符串的开头或一行的开头
$
字符串的结尾或一行的结尾
\A
字符串的开头
\Z
字符串的结尾
\b
空字符串的开头或一个单词的结尾
\B
非空字符串的开头或非一个单词的结尾,与\b相反
测试例子如下:
#python 3.6#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
from re_test_patterns import test_patterns
test_patterns(
'This is some text -- with punctuation.',
[(r'^\w+', 'word at start of string'),
(r'\A\w+', 'word at start of string'),
(r'\w+\S*$', 'word near end of string'),
(r'\w+\S*\Z', 'word near end of string'),
(r'\w*t\w*', 'word containing t'),
(r'\bt\w+', 't at start of word'),
(r'\w+t\b', 't at end of word'),
(r'\Bt\B', 't, not start or end of word')],
)
结果输出如下:
'^\w+' (word at start of string)
'This is some text -- with punctuation.'
'This'
'\A\w+' (word at start of string)
'This is some text -- with punctuation.'
'This'
'\w+\S*$' (word near end of string)
'This is some text -- with punctuation.'
..........................'punctuation.'
'\w+\S*\Z' (word near end of string)
'This is some text -- with punctuation.'
..........................'punctuation.'
'\w*t\w*' (word containing t)
'This is some text -- with punctuation.'
.............'text'
.....................'with'
..........................'punctuation'
'\bt\w+' (t at start of word)
'This is some text -- with punctuation.'
.............'text'
'\w+t\b' (t at end of word)
'This is some text -- with punctuation.'
.............'text'
'\Bt\B' (t, not start or end of word)
'This is some text -- with punctuation.'
.......................'t'
..............................'t'
.................................'t'