Regular expression in Python

How to use

Module import

import re

Regular expression object generation / matching

How to create a regular expression object and then match

#Generate
cmpObj = re.compile(r'a.c')
#matching
ret = cmpObj.match('abc')

Matching is possible without creating a regular expression object. However, if you use the same regular expression pattern many times in your program, it is more efficient to create and use a regular expression object.

#matching
ret = re.match(r'a.c', 'abc')

If the string matches the regular expression pattern, the match object is returned as the return value of match (). If there is no match, None will be returned.

Since match () checks whether the beginning of the string matches, it does not match in the following cases

#This does not match
ret = re.match(r'a.c', 'babc') 

Use search () to check if there is a match not only at the beginning of the string but also in the middle.

#This matches
ret = re.search(r'a.c', 'babc')
#When using a regular expression object
ret = cmpObj.search('babc')

Check if it matches

if ret : 
    print(ret) #If it matches
else :
    print('not match') #If there is no match

important point

Recommended Posts

Regular expression in Python
Regular expression in Python
Regular expression in regex.h
python regular expression memo
Start / end match in python regular expression
Use let expression in Python
Python 處 處 regular expression Notes
Use regular expressions in Python
Regular expression manipulation with Python
Regular expression symbolic group name in Python / Ruby
String replacement with Python regular expression
When using regular expressions in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
SendKeys in Python
Regular expression Greedy
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
[Python] Regular Expressions Regular Expressions
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Reproduce the Python regular expression r'\ w (? U)' in JavaScript
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
Regular expression re
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Overlapping regular expressions in Python and Java
Use print in a Python2 lambda expression
(Python) HTML reading and regular expression notes
Replace non-ASCII with regular expressions in Python
Don't use \ d in Python 3 regular expressions!
How to use regular expressions in Python