go-proto-validators icon indicating copy to clipboard operation
go-proto-validators copied to clipboard

when have "\" in regex, protoc will throw err" Invalid escape sequence"

Open chaoweili opened this issue 6 years ago • 6 comments

for example: repeated string pic_url_list = 2 [(validator.field) = {regex: "/^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-]*)*\/?$/"}];

this will return error: feeds_protocol.proto:323:83: Invalid escape sequence in string literal.

if i do not use "", everything works fine.

chaoweili avatar Apr 13 '18 12:04 chaoweili

I'm running into the same thing, but not using quotes gives me a different error:

pkg/proto/nks.proto:48:50: Error while parsing option value for "field": Expected string, got: /

Is there a fix for this?

erstaples avatar Jun 21 '19 16:06 erstaples

Hello @chaoweili and @erstaples. I've only very recently picked up this repository for maintenance. I'll try to address this issue in the near term.

Helcaraxan avatar Jul 09 '19 09:07 Helcaraxan

The quick fix in the mean time should be to specify your regex within back-ticks instead of double-quotes.

Helcaraxan avatar Jul 09 '19 09:07 Helcaraxan

Thanks for the response, @Helcaraxan . That doesn't work for me, unfortunately. My compiler really wants those quotes:

builder_api/builder_api.proto:113:29: Error while parsing option value for "field": Expected string, got: `

Here's the field in question:

    string kubernetes_version = 8 [
        (validator.field) = { regex: `/^v[0-9]{1}\.[0-9]{1,2}\.[0-9]{1,2}$/` }
    ];

erstaples avatar Aug 07 '19 17:08 erstaples

Reading your regular expression (RE) a few questions come to mind:

  • Why the / at the front and the head of the RE? The ^ and $ already express the need to match an entire line?
  • I believe that the following should work and give you the result you want:
    string kubernetes_version = 8 [
        (validator.field) = { regex: "^v[0-9]{1}\\.[0-9]{1,2}\\.[0-9]{1,2}$" }
    ];

Bear in mind that the string you provide in the regex validator is reused as is to instantiate a regexp.Regexp from the Go standard library so the RE should follow Go's RE syntax. Just wanted to make sure that was well understood, just in case. 🙂

Helcaraxan avatar Aug 07 '19 21:08 Helcaraxan

\\ in .proto file generated valid regex in Go code. Maybe add that to documentation and close this issue?

AlekSi avatar Jan 21 '20 06:01 AlekSi