0

Here, I've tried to create a regular expression that matches one particular string:

#This is the string that the regex is intended to match
theString = "..!-+!)|(!+-!.."

print(re.compile(theString).match(theString))

This produces an error instead of matching the string:

raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

Is there any way to generate a regular expression that matches just one specific string, like this one?

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • Not sure I understand the question. For example, the regex "apple" will only match the string "apple". – Tim Jones Mar 04 '14 at 01:27
  • Why do you want to use a regular expression? You could just use a simple search function if it is really just a specific string. – zchrykng Mar 04 '14 at 01:27
  • @TimJones `re.compile("..!-+!)|(!+-!..")` does not match the string `"..!-+!)|(!+-!.."`. – Anderson Green Mar 04 '14 at 01:28
  • 2
    The problem with that string is that it contains lots of characters that are "special" in regex syntax. – zchrykng Mar 04 '14 at 01:28
  • @zchrykng I'm using a regular expression because I need to generate a regex that I can use to [split another string without removing separators](http://stackoverflow.com/questions/4416425/how-to-split-string-with-some-seperator-but-without-removing-that-seperator-in-j). – Anderson Green Mar 04 '14 at 01:29
  • @AndersonGreen then pasztorpisti's answer is probably what you are looking for. – zchrykng Mar 04 '14 at 01:30
  • possible duplicate of [Escaping regex string in Python](http://stackoverflow.com/questions/280435/escaping-regex-string-in-python) – Anderson Green Mar 04 '14 at 02:23

1 Answers1

6
import re
your_string = "..!-+!)|(!+-!.."
your_regex_string = "^" + re.escape(your_string) + "$"
your_regex = re.compile(your_regex_string)
pasztorpisti
  • 3,760
  • 1
  • 16
  • 26