0

I have a regex to detect absolute path in CSS, with javascript it work, but not in GOLANG: this is my regex:

url\((?!['"]?(?:data|http|https):)['"]?([^'"\)]*)['"]?\)

In golang, when run it catch error:

error parsing regexp: invalid or unsupported Perl syntax: `(?!`

Does anyone known how to fix this error?

This is demo:

Demo in golang

This is demo work with other language, not golang:

https://regex101.com/r/WkbUuT/4

Enesy
  • 259
  • 3
  • 13
  • Go uses RE2, not PCRE. There is no fix, look arounds are not supported: https://github.com/google/re2/wiki/Syntax – Peter Sep 21 '19 at 08:03
  • Thank you, so can you please give me equivalent regex to my above one? – Enesy Sep 21 '19 at 08:04

1 Answers1

5

Go does not support a positive lookahead (?=.

To match the path if it does not start with data or http or https, one option is using an alternation first matching what you don't want and capture in group 1 what you want to keep.

url\((?:['"]?(?:https?|data):[^'"\)]+['"]?|['"]?([^'")]+)['"]?)\)

In parts

  • url\( Match url(
  • (?: Non capturing group
    • ['"]? Optional quote
    • (?:https?|data): Match http, https or data.
    • [^'"\)]+ Match 1+ times any char except ', " or )
    • ['"]? Optional quote
    • | Or
    • ['"]? Optional quote
    • ([^'")]+) Capture group 1, matching 1+ times any char except ', " or )
    • ['"]? Optional quote
  • ) Close group
  • \)

Regex demo

The path is in group 1.

Note that using ['"]? for both the opening and closing quotes means that it could also match when only the opening or closing is present as it is optional.

If you want only consistent matching where each opening quote is closed by a matching closing quote you might list all variations.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70