簡單介紹Python正則表達式
python正則表達式學習,python正則是我們常用的計算機語言,應用非常廣泛,下面的額文章就詳細的介紹用python正則表達式來做一些復雜字符串分析,提取想要的信息夠用就行,一下就是相關的詳細的介紹。
正則表達式中特殊的符號:
“.” 表任意字符
“^ ” 表string起始
“$” 表string 結束
“*” “+” “?” 跟在字符后面表示,0個——多個, 1個——多個, 0個或者1個
*?, +?, ?? 符合條件的情況下,匹配的盡可能少//限制*,+,?匹配的貪婪性
{m} 匹配此前的字符,重復m次
{m,n} m到n次,m,n可以省略
舉個例子 ‘a.*b’ 表示a開始,b結束的任意字符串
a{5} 匹配連續5個a
[] 表一系列字符 [abcd] 表a,b,c,d [^a] 表示非a
| A|B 表示A或者B , AB為任意的python正則表達式另外|是非貪婪的如果A匹配,則不找B
(…) 這個括號的作用要結合實例才能理解, 用于提取信息
- d [0-9]
- D 非 \d
- s 表示空字符
- S 非空字符
- \w [a-zA-Z0-9_]
- \W 非 \w
一:re的幾個函數
1: compile(pattern, [flags])
根據python正則表達式字符串 pattern 和可選的flags 生成正則表達式 對象生成正則表達式 對象(見二)其中flags有下面的定義:
I 表示大小寫忽略
L 使一些特殊字符集,依賴于當前環境
M 多行模式 使 ^ $ 匹配除了string開始結束外,還匹配一行的開始和結束
S “.“ 匹配包括‘\n’在內的任意字符,否則 . 不包括‘\n’
U Make \w, \W, \b, \B, \d, \D, \s and \S dependent on the Unicode character properties database
X 這個主要是表示,為了寫正則表達式,更可毒,會忽略一些空格和#后面的注釋
其中S比較常用應用形式如下
- import re
- re.compile(……,re.S)
2: match(pattern,string,[,flags])讓string匹配,pattern,后面分flag同compile的參數一樣返回MatchObject 對象
3: split( pattern, string[, maxsplit = 0])用pattern 把string 分開
- >>> re.split(‘\W+’, ‘Words, words, words.’)
- ['Words', 'words', 'words', '']
括號‘()’在pattern內有特殊作用,請查手冊
4:findall( pattern, string[, flags])比較常用,從string內查找不重疊的符合pattern正則表達式的表達式,然后返回list列表
5:sub( pattern, repl, string[, count])repl可以時候字符串,也可以式函數當repl是字符串的時候,就是把string 內符合pattern的子串,用repl替換了當repl是函數的時候,對每一個在string內的,不重疊的,匹配pattern的子串,調用repl(substring),然后用返回值替換
- substringre.sub(r’def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):’,
- … r’static PyObject*\npy_\1(void)\n{‘,
- … ‘def myfunc():’)
- ’static PyObject*\npy_myfunc(void)\n{‘
- >>> def dashrepl(matchobj):
- … if matchobj.group(0) == ‘-’: return ‘ ‘
- … else: return ‘-’
- >>> re.sub(‘-{1,2}’, dashrepl, ‘pro—-gram-files’)
- ‘pro–gram files’
二:re的幾個函數產生方式:
通過 re.compile(pattern,[flags])回match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配pattern的MatchObject
- split( string[, maxsplit = 0])
- findall( string[, pos[, endpos]])
- sub( repl, string[, count = 0])
這幾個函數和re模塊內的相同,只不過是調用形式有點差別re.幾個函數和 正則表達式對象的幾個函數,功能相同,但同一程序如果多次用的這些函數功能,正則表達式對象的幾個函數效率高些#p#
三:matchobject
通過 re.match(……) 和 re.compile(……).match返回該對象有如下方法和屬性:
方法:
- group( [group1, ...])
- groups( [default])
- groupdict( [default])
- start( [group])
- end( [group])
的***方法,就是舉個例子
- matchObj = re.compile(r”(?P\d+)\.(\d*)”)
- m = matchObj.match(‘3.14sss’)
- #m = re.match(r”(?P\d+)\.(\d*)”, ‘3.14sss’)
- print m.group()
- print m.group(0)
- print m.group(1)
- print m.group(2)
- print m.group(1,2)
- print m.group(0,1,2)
- print m.groups()
- print m.groupdict()
- print m.start(2)
- print m.string
輸出如下:
- 3.14
- 3.14
- 3
- 14
- (‘3′, ‘14′)
- (‘3.14′, ‘3′, ‘14′)
- (‘3′, ‘14′)
- {‘int’: ‘3′}
- 2
- 3.14sss
所以group() 和group(0)返回,匹配的整個表達式的字符串
另外group(i) 就是python正則表達式中用第i個“()” 括起來的匹配內容
(‘3.14′, ‘3′, ‘14′)最能說明問題了。
以上的文章就是我們對其的相關介紹,希望大家有所收獲。
【編輯推薦】