Home > Backend Development > Golang > How to Work Around Lookarounds in Go Regex?

How to Work Around Lookarounds in Go Regex?

Barbara Streisand
Release: 2024-11-30 16:45:11
Original
203 people have browsed it

How to Work Around Lookarounds in Go Regex?

Error Parsing Regexp: Invalid Perl Syntax (?!

When attempting to use a regular expression in Go, an error is encountered:

error parsing regexp: invalid or unsupported Perl syntax: (?!
Copy after login

This error occurs specifically with the following regex:

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

Solution

The issue arises because Go regex doesn't support lookarounds, unlike Perl. Lookarounds are assertions that check the surrounding text without consuming it.

To work around this limitation, use a different approach:

Firstly, compile two separate regular expressions:

first := regexp.MustCompile(`^On\s(.+?)wrote:$`)
second := regexp.MustCompile(`^On.*On\s.+?wrote:`)
Copy after login

Then, perform the following steps:

  1. Check if first matches the string.
  2. If it does, proceed to step 3. Otherwise, the string matches neither expression, so return true.
  3. Check if second matches the string.
  4. If it does, the string matches the second expression, so return false. Otherwise, return true.

Alternatively, you can use an optional capturing group to simplify the process:

regex := regexp.MustCompile(`^On(.*On)?\s.+?wrote:`)
Copy after login

Check for a match and return true if:

  • Group 1 ends with On.
  • Group 1 doesn't exist or doesn't end with On.

Otherwise, return false.

The above is the detailed content of How to Work Around Lookarounds in Go Regex?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template