1

im trying out the fuzzy function of the new regex module. in this case, i want there to find a match for all strings with <= 1 errors, but i'm having trouble with it

import regex

statement = 'eol the dark elf'
test_1 = 'the dark'
test_2 = 'the darc' 
test_3 = 'the black'

print regex.search('{}'.format(test_1),statement).group(0) #works

>>> 'the dark' 

print regex.search('{}'.format(test_1){e<=1},statement).group(0)

>>> print regex.search('{}'.format(test_1){e<=1},statement).group(0) #doesn't work 
                                          ^
SyntaxError: invalid syntax 

i have also tried

print regex.search('(?:drk){e<=1}',statement).group(0) #works
>>> 'dark'

but this . . .

print regex.search(('(?:{}){e<=1}'.format(test_1)),statement).group(0) #doesn't work
>>> SyntaxError: invalid syntax
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
O.rka
  • 29,847
  • 68
  • 194
  • 309

1 Answers1

1

In your first snippet, you forgot to put the {e<=1} in a string. In your final snippet, I think the problem is, that format tries to deal with the {e<=1} itself. So either you use concatenation:

print regex.search(test_1 + '{e<=1}', statement).group(0)

or you escape the literal braces, by doubling them:

print regex.search('{}{{e<=1}}'.format(test_1), statement).group(0)

This can then easily be extended to

print regex.search('{}{{e<={}}}'.format(test_1, num_of_errors), statement).group(0)
Martin Ender
  • 43,427
  • 11
  • 90
  • 130
  • i'm a little confused on how to make the error number a variable. lets say error = 2 ... it doesn't work when i try '{e<={}}'.format(error) – O.rka Jul 03 '13 at 20:33
  • @draconisthe0ry I just realized, literal braces can be escaped by doubling them. I'll edit the answer – Martin Ender Jul 03 '13 at 20:40