python Python Regexhttp://chimera.labs.oreilly.com/books/1230000000393/ch02.html#_discussion_21

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python Regexhttp://chimera.labs.oreilly.com/books/1230000000393/ch02.html#_discussion_21相关的知识,希望对你有一定的参考价值。

match.py
replace.py
search.py
############################
# Test Match
############################

## Regex Match
text2 = 'Nov 27, 2012'
import re
if re.match(r'\d+/\d+/\d+', text1): print('yes')
#=> yes

# you can compile the regex for speed
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(text1): print('yes')
#=> yes


## Simple search
text = 'yeah, but no, but yeah, but no, but yeah'

# Exact match
text == 'yeah'  #=> False

# Match at start or end
text.startswith('yeah') #=> True
text.endswith('no') #=>  False

# Search for the location of the first occurrence
text.find('no') #=> 10
############################
# Replace
############################
# regex
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
#=> 'Today is 2012-11-27. PyCon starts 2013-3-13.'


# simple
text = 'yeah, but no, but yeah, but no, but yeah'
text.replace('yeah', 'yep')
#=> 'yep, but no, but yep, but no, but yep'

###########################
## Extract mathed elements
############################
# extract sub patterns
m = datepat.match('11/27/2012')
( m.group(0),  m.group(1), m.group(2),  m.group(3)) 
#=> ('11/27/2012', '11', '27', '2012')
>>> month, day, year = m.groups() # month, day, year is defined

# Find all matches (notice splitting into tuples)
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
datepat.findall(text) #=> [('11', '27', '2012'), ('3', '13', '2013')]

以上是关于python Python Regexhttp://chimera.labs.oreilly.com/books/1230000000393/ch02.html#_discussion_21的主要内容,如果未能解决你的问题,请参考以下文章

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python