From charlesreid1

(Created page with "Regular expressions in Python.")
 
No edit summary
Line 1: Line 1:
[[Regular expressions]] in Python.
[[Regular expressions]] in Python.
==Extracting substring from strings using re==
Suppose we have a string like "thing2_2017-04-09_05-04-67.csv" and we want to extract tokens from the filename (thing2, 2017, 04, 09, etc).
To extract particular tokens using a regular expression, we can use <code>re.findall(regular_expression,string)</code>. For example, the regular expression <code>[0-9]{4}</code> looks for the digits 0-9 occurring exactly 4 times.
<pre>
>>> z = "thing2_2017-04-09_05-04-67.csv"
>> re.findall(r'[0-9]{4}', z)
['2017']
</pre>

Revision as of 18:16, 12 April 2017

Regular expressions in Python.

Extracting substring from strings using re

Suppose we have a string like "thing2_2017-04-09_05-04-67.csv" and we want to extract tokens from the filename (thing2, 2017, 04, 09, etc).

To extract particular tokens using a regular expression, we can use re.findall(regular_expression,string). For example, the regular expression [0-9]{4} looks for the digits 0-9 occurring exactly 4 times.

>>> z = "thing2_2017-04-09_05-04-67.csv"
>> re.findall(r'[0-9]{4}', z)
['2017']