# File: re-example-1.py import re text = "The Attila the Hun Show" # a single character m = re.match(".", text) if m: print repr("."), "=>", repr(m.group(0)) # any string of characters m = re.match(".*", text) if m: print repr(".*"), "=>", repr(m.group(0)) # a string of letters (at least one) m = re.match("\w+", text) if m: print repr("\w+"), "=>", repr(m.group(0)) # a string of digits m = re.match("\d+", text) if m: print repr("\d+"), "=>", repr(m.group(0)) # File: re-example-2.py import re text ="10/15/99" m = re.match("(\d{2})/(\d{2})/(\d{2,4})", text) if m: print m.group(1, 2, 3) # File: re-example-3.py import re text = "Example 3: There is 1 date 10/25/95 in here!" m = re.search("(\d{1,2})/(\d{1,2})/(\d{2,4})", text) print m.group(1), m.group(2), m.group(3) month, day, year = m.group(1, 2, 3) print month, day, year date = m.group(0) print date # File: re-example-4.py import re text = "you're no fun anymore..." # literal replace (string.replace is faster) print re.sub("fun", "entertaining", text) # collapse all non-letter sequences to a single dash print re.sub("[^\w]+", "-", text) # convert all words to beeps print re.sub("\S+", "-BEEP-", text) # File: re-example-5.py import re import string text = "a line of text\\012another line of text\\012etc..." def octal(match): # replace octal code with corresponding ASCII character return chr(string.atoi(match.group(1), 8)) octal_pattern = re.compile(r"\\(\d\d\d)") print text print octal_pattern.sub(octal, text) # File: re-example-6.py import re, string def combined_pattern(patterns): p = re.compile( string.join(map(lambda x: "("+x+")", patterns), "|") ) def fixup(v, m=p.match, r=range(0,len(patterns))): try: regs = m(v).regs except AttributeError: return None # no match, so m.regs will fail else: for i in r: if regs[i+1] != (-1, -1): return i return fixup # # try it out! patterns = [ r"\d+", r"abc\d{2,4}", r"p\w+" ] p = combined_pattern(patterns) print p("129391") print p("abc800") print p("abc1600") print p("python") print p("perl") print p("tcl")
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question