Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何生成匹配一个特定字符串的正则表达式_Python_Regex - Fatal编程技术网

Python 如何生成匹配一个特定字符串的正则表达式

Python 如何生成匹配一个特定字符串的正则表达式,python,regex,Python,Regex,在这里,我尝试创建一个与一个特定字符串匹配的正则表达式: #This is the string that the regex is intended to match theString = "..!-+!)|(!+-!.." print(re.compile(theString).match(theString)) 这将生成一个错误,而不是匹配字符串: raise error, v # invalid expression sre_constants.error: unbalanced

在这里,我尝试创建一个与一个特定字符串匹配的正则表达式:

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

print(re.compile(theString).match(theString))
这将生成一个错误,而不是匹配字符串:

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

有没有办法生成一个只匹配一个特定字符串的正则表达式,比如这个字符串?

我不太明白这个问题。例如,正则表达式“apple”将只与字符串“apple”匹配。为什么要使用正则表达式?如果它实际上只是一个特定的字符串,您可以只使用一个简单的搜索函数。@TimJones
re.compile(…!-+!)|(!+-!)
与字符串
。!-+!)|(!+-!)
不匹配。该字符串的问题是它包含许多“特殊”字符在正则表达式语法中。@zchrykng我使用正则表达式,因为我需要生成一个正则表达式,我可以使用它来解决这个问题。我不确定我是否理解这个问题。例如,正则表达式“apple”将只匹配字符串“apple”。为什么要使用正则表达式?如果它实际上只是一个特定的字符串,则可以使用一个简单的搜索函数。@TimJones
re.compile(“…!!+!)|(!+!-!)|(!+!!)|(!+!-!)
”与字符串不匹配。!-+)|(!+-!-!!!-!“。该字符串的问题是它包含大量“特殊”字符在正则表达式语法中。@zchrykng我使用正则表达式,因为我需要生成一个正则表达式,我可以使用它来进行计算。
import re
your_string = "..!-+!)|(!+-!.."
your_regex_string = "^" + re.escape(your_string) + "$"
your_regex = re.compile(your_regex_string)