Regular expressions are used for pattern matching.The Python "re" module provides regular expression support.
import re
s1 = 'this is a nice line!'
pat1 = 'nice'
print re.search(pat1, s1)
If pattern matching is successful a match object is returned else the function returns None.
pat1 = r'^is'
print re.search(pat1, s1)
'r' before the string gives a special meaning to it. By using that we say the string is raw or the special characters used withing the string doesn't have special meaning.
Ordinary characters just match themselves exactly.
The characters which do not match themselves because they have special meanings are:
. ^ $ * + ? { [ ] \ | ( )
import re
s1 = 'this is a nice line!'
pat1 = 'nice'
print re.search(pat1, s1)
If pattern matching is successful a match object is returned else the function returns None.
pat1 = r'^is'
print re.search(pat1, s1)
'r' before the string gives a special meaning to it. By using that we say the string is raw or the special characters used withing the string doesn't have special meaning.
Ordinary characters just match themselves exactly.
The characters which do not match themselves because they have special meanings are:
. ^ $ * + ? { [ ] \ | ( )
- . (a period) -- matches any single character except newline '\n'
- \w -- (lowercase w) matches a "word" character: a letter or digit or underscore. Note that although "word" is the mnemonic for this, it only matches a single word char, not a whole word. \W (upper case W) matches any non-word character.
- \b -- boundary between word and non-word
- \s -- (lowercase s) matches a single whitespace character -- space, newline, return, tab, form. \S (upper case S) matches any non-whitespace character.
- \t, \n, \r -- tab, newline, return
- \d -- decimal digit [0-9]
- ^ = start, $ = end -- match the start or end of the string
- \ -- inhibit the "specialness" of a character. So, for example, use \. to match a period or \\ to match a slash. If you are unsure if a character has special meaning, such as '@', you can put a slash in front of it, \@, to make sure it is treated just as a character.






0 comments:
Post a Comment