【问题标题】:How to generate a regular expression that matches one specific string如何生成匹配一个特定字符串的正则表达式
【发布时间】:2014-04-05 08:18:41
【问题描述】:

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

#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 我正在使用正则表达式,因为我需要生成一个可以用于split another string without removing separators 的正则表达式。

标签: python regex


【解决方案1】:
import re
your_string = "..!-+!)|(!+-!.."
your_regex_string = "^" + re.escape(your_string) + "$"
your_regex = re.compile(your_regex_string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多