0

I am trying to match string with mypattern, somehow I do not get correct result. Can you please point where am I wrong?

import re
mypattern = '_U_[R|S]_data.csv'
string =  'X003_U_R_data.csv'
re.match(mypattern, string)
learner
  • 2,582
  • 9
  • 43
  • 54
  • 2
    What is your expected output? – C_Z_ Aug 14 '15 at 17:08
  • 4
    [`re.match`](https://docs.python.org/2/library/re.html#re.match) matches only *from the beginning of the string*. Use [`re.search`](https://docs.python.org/2/library/re.html#re.search) instead to search the whole string. – Lukas Graf Aug 14 '15 at 17:09

1 Answers1

1

I like to compile the regex statement first. Then I do whatever kind of matching/searching I would like.

mypattern = re.compile(ur'_U_[R|S]_data.csv')

Then

re.search(mypattern, string)

Here's a great website for regex creation- https://regex101.com/#python

Darec
  • 101
  • 6
  • He doesn't have to compile it though. He can use re.search without compiling. Look: https://docs.python.org/2/library/re.html#re.MatchObject.end – nonamorando Aug 14 '15 at 17:11
  • You are correct sir. Stupid mistake on my part. I changed my wording of the answer. – Darec Aug 14 '15 at 17:15
  • https://regex101.com/#python. This Link was useful. Thanks – learner Aug 14 '15 at 18:23
  • I believe what was wrong with his code was that there were no 'ur' flags to indicate Unicode and Raw string, so the []'s were literal rather than symbolic – nonamorando Aug 14 '15 at 21:46