Regular expressions: Difference between revisions

added (real) python example.
(removed poor csharp example, i'm going to add it soon (Guga360.))
(added (real) python example.)
Line 372:
 
=={{header|Python}}==
<lang python>import re
{{works with|Python|2.5}}
Setup
 
strstring = 'I"This amis a string'"
import re
str = 'I am a string'
 
if re.search(r'string$', strstring):
Test
print "Ends with 'string'."
 
strstring = re.sub(r'" a '", '" another '", strstring)
if re.search(r'string$', str):
print "Ends with 'string'"</lang>
 
Test, storing the compiled regular expression in a variable
 
regex = re.compile(r'string$')
if regex.search(str):
print "Ends with 'string'"
 
To find all matches rather than just the first match, use re.findall rather than re.search.
 
Substitute
 
str = re.sub(r' a ', ' another ', str)
 
All instances of the specified pattern are replaced. To limit the number of instances replaced, specify the fourth argument to sub, the maximum number of replacements. To make a case-insensitive replacement, place (?i) at the beginning of the regular expression.
 
Substitute, storing the compiled regular expression in a variable
 
regex = re.compile(r' a ')
str = regex.sub(' another ', str)
 
'''Note:''' re.match() and regex.match() imply a "^" at the beginning of the regular expression. re.search() and regex.search() do not.
 
=={{header|Raven}}==
Anonymous user