Python/Regex: Difference between revisions

From Fundamental Ramen
Jump to navigation Jump to search
Line 27: Line 27:
     pass
     pass
</source>
</source>
* Cannot use with pattern.search(...) as m.
* Cannot use with pattern.match(...) as m.


= To Replace =
= To Replace =

Revision as of 07:56, 31 May 2018

To Match

import re

sample1 = '2018-05-31'
sample2 = 'Today is 2018-51-31.'
pattern = re.compile('(\d{4})-(\d{2})-(\d{2})')

m = pattern.search(sample1)
if m:
    print('Found pattern in sample1 between {}~{}.'.format(m.span()[0], m.span()[1]))
    print('m[1]={}, m[2]={}, m[3]={}'.format(m[1], m[2], m[3]))

m = pattern.search(sample2)
if m:
    print('Found pattern in sample1 between {}~{}.'.format(m.span()[0], m.span()[1]))
    print('m[1]={}, m[2]={}, m[3]={}'.format(m[1], m[2], m[3]))

m = pattern.match(sample1)
if m:
    print('Matched pattern sample1.')
    print('m[1]={}, m[2]={}, m[3]={}'.format(m[1], m[2], m[3]))

m = pattern.match(sample2)
if m:
    # won't be matched
    pass
  • Cannot use with pattern.search(...) as m.
  • Cannot use with pattern.match(...) as m.

To Replace

ns = re.sub('o+', '_', 'doooooog')