程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Re module in python (2)

編輯:Python

1. finditer() function

Search string , Return to one Match object Of iterator ( Contains the starting and ending positions of the match ). Find all substrings of regular matches , Return them as an iterator .

Format :

re.finditer(pattern, string, flags=0)

for example :

import re
itext = re.finditer(r'\d+','12 edueduedu44coder deducoder, 11skdh ds 12') # Match all the numbers 
for i in itext:
print(i)
print(i.group())
print(i.span()) #span() Returns a tuple containing a match ( Start , end ) The location of 

The operation results are as follows :

<re.Match object; span=(0, 2), match='12'>
12
(0, 2)
<re.Match object; span=(12, 14), match='44'>
44
(12, 14)
<re.Match object; span=(31, 33), match='11'>
11
(31, 33)
<re.Match object; span=(43, 45), match='12'>
12
(43, 45)

2. split() function

According to the substring that can be matched , take string Split and return to list .

Format :

re.split(pattern, string)

have access to re.split To split the string , Such as :re.split(r’\s+', text) The string , Divide into a list of words by spaces .

Number as separator , Split the string :

print(re.split(r'\d+','asas2kdjs4jds5djdfj1djf0'))

The operation results are as follows :

['asas', 'kdjs', 'jds', 'djdfj', 'djf', '']

3. sub() function

Use re Replace string After each matching substring in , Return the replaced string .

Format :

re.sub(pattern, repl, string, count)

use - replace , as follows :

import re
text = "aaa,bbb,ccc,ddd"
print(re.sub(r',', '-', text))

The operation results are as follows :

aaa-bbb-ccc-ddd

4. subn() function

Returns the number of substitutions .

Format :

subn(pattern, repl, string, count=0, flags=0)
  • explain : use A Replace 123 Medium 1, The result is A23,repl It means A.

Replace all the numbers with A:

print(re.subn('\d','A','1asd2dkjf34'))

The operation results are as follows :

('AasdAdkjfAA', 4)
  • subn() Not only does it return the replaced string , It also returns the number of replacements .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved