【问题标题】:error parsing regexp: invalid or unsupported Perl syntax: `(?!`解析正则表达式时出错:Perl 语法无效或不受支持:`(?!`
【发布时间】:2016-12-20 09:48:08
【问题描述】:

当我在 golang 中尝试这个正则表达式时,我遇到了正则表达式解析错误。

解析正则表达式时出错:Perl 语法无效或不受支持:(?!

regexp.MustCompile("^(?!On.*On\\s.+?wrote:)(On\\s(.+?)wrote:)$"),

谁能告诉我为什么它不起作用并帮助我解决这个问题?

谢谢

【问题讨论】:

  • go regexp 包使用 RE2 语法,而不是 PCRE github.com/google/re2/wiki/Syntax
  • (?!re) before text not matching re (NOT SUPPORTED) 来自页面here
  • @svasa 有没有其他方法可以让它工作?
  • @JimB 感谢您的链接。有什么替代方法吗?
  • 使用regexp.MustCompile("^On\\s(.+?)wrote:$")regexp.MustCompile("^On.*On\\s.+?wrote:") 并检查第一个是否为真,第二个是否为假。

标签: regex go


【解决方案1】:

Go 正则表达式不支持环视。

作为一种解决方法,您可以使用

regexp.MustCompile(`^On\s(.+?)wrote:$`)

regexp.MustCompile(`^On.*On\s.+?wrote:`)

并检查第一个是否与字符串匹配,而第二个不匹配。

您还可以添加一个可选的捕获组(.*On)?

regexp.MustCompile(`^On(.*On)?\s.+?wrote:`)

并检查是否存在匹配,如果 Group 1 以 On 结尾,则返回 true - 如果是,则返回 false,否则返回 true em>。

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2023-01-02
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    相关资源
    最近更新 更多