GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Python - Regular Expressions
Selected Reading
Python - Regular ExpressionsA regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expression are popularly known as regex or regexp. Usually, such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. Large scale text processing in data science projects requires manipulation of textual data. The regular expressions processing is supported by many programming languages including Python. Python's standard library has re module for this purpose. Since most of the functions defined in re module work with raw strings, let us first understand what the raw strings are. Raw StringsRegular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. Python on the other hand uses the same character as escape character. Hence Python uses the raw string notation. A string become a raw string if it is prefixed with r or R before the quotation symbols. Hence 'Hello' is a normal string were are r'Hello' is a raw string. >>> normal="Hello" >>> print (normal) Hello >>> raw=r"Hello" >>> print (raw) Hello In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually interprets the escape sequence, where as the raw string doesn't process the escape character. >>> normal="Hello\nWorld" >>> print (normal) Hello World >>> raw=r"Hello\nWorld" >>> print (raw) Hello\nWorld In the above example, when a normal string is printed the escape character '\n' is processed to introduce a newline. However because of the raw string operator 'r' the effect of escape character is not translated as per its meaning. MetacharactersMost letters and characters will simply match themselves. However, some characters are special metacharacters, and don't match themselves. Meta characters are characters having a special meaning, similar to * in wild card. Here's a complete list of the metacharacters − . ^ $ * + ? { } [ ] \ | ( )
The square bracket symbols[ and ] indicate a set of characters that you wish to match. Characters can be listed individually, or as a range of characters separating them by a '-'.
'\'is an escaping metacharacter. When followed by various characters it forms various special sequences. If you need to match a [ or \, you can precede them with a backslash to remove their special meaning: \[ or \\. Predefined sets of characters represented by such special sequences beginning with '\' are listed below −
Python's re module provides useful functions for finding a match, searching for a pattern, and substitute a matched string with other string etc. The re.match() FunctionThis function attempts to match RE pattern at the start of string with optional flags. Following is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters −
The re.match() function returns a match object on success, None on failure. A match object instance contains information about the match: where it starts and ends, the substring it matched, etc. The match object's start() method returns the starting position of pattern in the string, and end() returns the endpoint. If the pattern is not found, the match object is None. We use group(num) or groups() function of match object to get matched expression.
Exampleimport re
line = "Cats are smarter than dogs"
matchObj = re.match( r'Cats', line)
print (matchObj.start(), matchObj.end())
print ("matchObj.group() : ", matchObj.group())
It will produce the following output − 0 4 matchObj.group() : Cats The re.search() FunctionThis function searches for first occurrence of RE pattern within the string, with optional flags. Following is the syntax for this function − re.search(pattern, string, flags=0) Here is the description of the parameters −
The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get the matched expression.
Exampleimport re
line = "Cats are smarter than dogs"
matchObj = re.search( r'than', line)
print (matchObj.start(), matchObj.end())
print ("matchObj.group() : ", matchObj.group())
It will produce the following output − 17 21 matchObj.group() : than Matching Vs SearchingPython offers two different primitive operations based on regular expressions, match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default). Exampleimport re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print ("match --> matchObj.group() : ", matchObj.group())
else:
print ("No match!!")
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
print ("search --> searchObj.group() : ", searchObj.group())
else:
print ("Nothing found!!")
When the above code is executed, it produces the following output − No match!! search --> matchObj.group() : dogs The re.findall() FunctionThe findall() function returns all non-overlapping matches of pattern in string, as a list of strings or tuples. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. Syntaxre.findall(pattern, string, flags=0) Parameters
Exampleimport re string="Simple is better than complex." obj=re.findall(r"ple", string) print (obj) It will produce the following output − ['ple', 'ple'] Following code obtains the list of words in a sentence with the help of findall() function. import re string="Simple is better than complex." obj=re.findall(r"\w*", string) print (obj) It will produce the following output − ['Simple', '', 'is', '', 'better', '', 'than', '', 'complex', '', ''] The re.sub() FunctionOne of the most important re methods that use regular expressions is sub. Syntaxre.sub(pattern, repl, string, max=0) This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max is provided. This method returns modified string. Exampleimport re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print ("Phone Num : ", num)
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print ("Phone Num : ", num)
It will produce the following output − Phone Num : 2004-959-559 Phone Num : 2004959559 ExampleThe following example uses sub() function to substitute all occurrences of is with was word − import re string="Simple is better than complex. Complex is better than complicated." obj=re.sub(r'is', r'was',string) print (obj) It will produce the following output − Simple was better than complex. Complex was better than complicated. The re.compile() FunctionThe compile() function compiles a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods. Syntaxre.compile(pattern, flags=0) Flags
The sequence − prog = re.compile(pattern) result = prog.match(string) is equivalent to − result = re.match(pattern, string) But using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program. Exampleimport re string="Simple is better than complex. Complex is better than complicated." pattern=re.compile(r'is') obj=pattern.match(string) obj=pattern.search(string) print (obj.start(), obj.end()) obj=pattern.findall(string) print (obj) obj=pattern.sub(r'was', string) print (obj) It will produce the following output − 7 9 ['is', 'is'] Simple was better than complex. Complex was better than complicated. The re.finditer() FunctionThis function returns an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. Syntaxre.finditer(pattern, string, flags=0) Exampleimport re string="Simple is better than complex. Complex is better than complicated." pattern=re.compile(r'is') iterator = pattern.finditer(string) print (iterator ) for match in iterator: print(match.span()) It will produce the following output − (7, 9) (39, 41) Use Cases of Python RegexFinding all Adverbsfindall() matches all occurrences of a pattern, not just the first one as search() does. For example, if a writer wanted to find all of the adverbs in some text, they might use findall() in the following manner − import re text = "He was carefully disguised but captured quickly by police." obj = re.findall(r"\w+ly\b", text) print (obj) It will produce the following output − ['carefully', 'quickly'] Finding words starting with vowelsimport re text = 'Errors should never pass silently. Unless explicitly silenced.' obj=re.findall(r'\b[aeiouAEIOU]\w+', text) print (obj) It will produce the following output − ['Errors', 'Unless', 'explicitly'] Regular Expression Modifiers: Option FlagsRegular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these −
Regular Expression PatternsExcept for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Python −
Regular Expression ExamplesLiteral characters
Character classes
Special Character Classes
Repetition Cases
Nongreedy repetitionThis matches the smallest number of repetitions −
Grouping with Parentheses
BackreferencesThis matches a previously matched group again −
Alternatives
AnchorsThis needs to specify match position.
Special Syntax with Parentheses
Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |