Regular Expression Tutorial for Python 2.5
Regular expressions are strings of symbols that signify patterns in text. By using regular expressions, programmers can extend string searches beyond simple word matching. Regular expressions can define searches for word lengths, vowel usage, punctuation, and so on. Python 2.5 has a regular expression module, "re," which encapsulates methods useful to preforming regular expression searches.
Instructions
-
-
1
Import the regular expression module, and create a search string. Enter the following into the Python IDE:
>>>import re
>>>ex_string = "this is our 123 example string"
The first command imports the regular expression module into the current program, enabling the programmer to utilize its functions. The "ex_string" variable will be the test string to search.
-
2
Attempt to find a pattern in the example string using the "re" library:
>>>import re
>>>ex_string = "this is our 123 example string"
>>>match = re.match(".*", ex_string)
>>>repr(match.group(0))
this is our 123 example string
The match method takes a regular expression in quotations (in this case, ".*" which searches for an entire string of characters) and prints the first found match of the pattern.
-
-
3
Change the match pattern, and add a search for a substring:
>>>import re
>>>ex_string = "this is our 123 example string"
>>>match = re.search("\d\d\d", ex_string)
>>>repr(match.group(0))
123
The "search" method will search for the first instance of a substring matching a pattern and return that substring. In this example, the regular expression "\d\d\d" tells the method to search for any substring consisting of 3 digits together (the only one being "123").
-
1
References
- Photo Credit Jupiterimages/Photos.com/Getty Images