by
1
7
3,427
2
Top 1% !
Popular
Famous
Tagged
Easy-to-find
Specified
OpenSource
Popularity: 3878th place

Published on:

Architecturex86_64
LanguagePython
LicenseMIT_X11
OSLinux

Regular Expression In Python - Simple Grouping

This python code shows how to define a regular expression path and have it applied to some string.

The regex is defined using the compile built-in method of re library.

In the following example some groups are used to parse information from filename strings listed by 'ls' linux command.

Exception will raise if no match will be found.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11237/Regular-Expression-In-Python---Simple-Gr?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import os, re # Assume to have some file names listed # The matching path is: <id>_<name>_<code>.txt # Define regex my_regExp = re.compile(r'(?P<id>^[^_]*)_(?P<name>[^.]*)_(?P<code>[^.]*).txt') for myFile in os.popen('ls -F /some/path').readlines(): id= '' name= '' code= '' try: id= my_regExp.match(myFile).group('id') except: msgErr='Error on id - ' + myFile try: name= my_regExp.match(myFile).group('name') except: msgErr='Error on name - ' + myFile try: code= my_regExp.match(myFile).group('code') except: msgErr='Error on code- ' + myFile
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus