感覺這正規表示式,還是要多實踐,水平才能提高。
現在只是練習,知道其運用場合,掌握中心思想就差不多了。
附兩個鬆散正規表示式樣例:
>>> pattern = '''^ # beginning of string
m # thousands - 0 to 3 ms
(cm|cd|d?c) # hundreds - 900 (cm), 400 (cd), 0-300 (0 to 3 cs),
# or 500-800 (d, followed by 0 to 3 cs)
(xc|xl|l?x) # tens - 90 (xc), 40 (xl), 0-30 (0 to 3 xs),
# or 50-80 (l, followed by 0 to 3 xs)
(ix|iv|v?i) # ones - 9 (ix), 4 (iv), 0-3 (0 to 3 is),
# or 5-8 (v, followed by 0 to 3 is)
$ # end of string
'''>>> re.search(pattern, 'm', re.verbose) ①
<_sre.sre_match object at>
>>> re.search(pattern, 'mcml***ix', re.verbose) ②
<_sre.sre_match object at>
>>> re.search(pattern, 'mmmdcccl***viii', re.verbose) ③
<_sre.sre_match object at>
>>> re.search(pattern, 'm') ④
~~~~~~~~~~~~~~~~~~~~~~~~
>>> phonepattern = re.compile(r'''# don't match beginning of string, number can start anywhere
(\d) # area code is 3 digits (e.g. '800')
\d* # optional separator is any number of non-digits
(\d) # trunk is 3 digits (e.g. '555')
\d* # optional separator
(\d) # rest of number is 4 digits (e.g. '1212')
\d* # optional separator
(\d*) # extension is optional and can be any number of digits
$ # end of string
''', re.verbose)
>>> phonepattern.search('work 1-(800) 555.1212 #1234').groups() ①
('800', '555', '1212', '1234')
>>> phonepattern.search('800-555-1212') ②
('800', '555', '1212', '')
正規表示式備忘
1 為萬用字元,表示任何乙個字元,例如 a.c 可以匹配 anc abc acc 2 在內可以指定要求匹配的字元,例如 a nbc c 可以匹配 anc abc acc 但不可以匹配 ancc a到z可以寫成 a z 0到9可以寫成 0 9 3 數量限定符號,表示匹配次數 或者叫做長度 的符號 包括...
Python正規表示式練習
表示匹配任意字元,除了換行符,當re.dotall標記被指定時,則可以匹配包括換行符的任意字元。import re a xy123 b re.findall x.a c re.findall x.a print b print c 輸出結果 xy12 xy1 的使用舉例 匹配前乙個字元0次或無限次 ...
備忘(五)正規表示式
正規表示式 regular expression 是一種功能強大的字串樣式比較技術。正規表示式最早是從unix系統被開發出來的。它是由一群特殊符號所組成的字串,表示特定的文字樣式,被用於比較某段字串或文章裡,符合正規表示式所代表的樣式文字,例如,乙個簡單的正規表示式 1 9 可以用來表示字串中1 9...