0

I am reading in lines from a file each of which are formatted like this:

array_name[0]
array_name[1]

How can I do an exact match on this string in python? I've tried this:

if re.match(line, "array_name[0]")  

but it seems to match all the time without taking the parts in bracket ([0], [1], etc.) into account

TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
KAM
  • 115
  • 1
  • 3
  • 5

1 Answers1

1

re.escape from the re module is a useful tool for automatically escaping characters that the regex engine considers special. From the docs:

re.escape(pattern)

Escape all the characters in pattern except ASCII letters and numbers. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

In [1]: re.escape("array_name[0]")
Out[1]: 'array_name\\[0\\]'

Also, you've reversed the order of your arguments. You'll need your pattern to come first, followed by the text you want to match:

re.match(re.escape("array_name[0]"), line)

Example:

In [2]: re.match(re.escape("array_name[0]"), 'array_name[0] in a line')
Out[2]: <_sre.SRE_Match object; span=(0, 13), match='array_name[0]'>
cs95
  • 379,657
  • 97
  • 704
  • 746