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?

有帮助吗?

解决方案

import re
your_string = "..!-+!)|(!+-!.."
your_regex_string = "^" + re.escape(your_string) + "$"
your_regex = re.compile(your_regex_string)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top