skip to Main Content

I use the following regex:
/https{1}://(?:$INSTANCE$)(?:/w+){0,255}(?:?w+=w+){0,1}(?:&w+=w+){0,255}/ysg
and the following url-like structure for a match:
https://$INSTANCE$/eng/route?param=val&parameter3=value&prmtr=value
event though the regex is valid, Angular keeps giving this error:
SyntaxError: nothing to repeat

I validated the regex using this site: https://regex101.com/r/6x4kP2/1

Anyone know what is wrong with the regex?

The code where I use it:

patternCustomTSConfigURL = "https{1}://(?:$INSTANCE$)(?:/w+){0,255}(?:?w+=w+){0,1}(?:&w+=w+){0,255}",
    this.exampleForm = new FormGroup({
       url: new FormControl(this.url, [
          Validators.required,
          Validators.minLength(5),
          Validators.maxLength(255),
          Validators.pattern(patternCustomTSConfigURL)
        ])
    });

2

Answers


  1. You have to be careful with escaping characters in JavaScript. When copy pasting regex from internet, special characters usually aren’t escaped, so you have to modify it manually.

    Check the following: What does the "Nothing to repeat" error mean when using a regex in javascript?

    Login or Signup to reply.
  2. Like @chuftica already mentioned you have to be very careful escaping characters.

    As per mdn below two are same

    const re = /w+/;
    // OR
    const re = new RegExp("\w+");
    

    So, you have to use your regEx like below when it’s a string format

    patternCustomTSConfigURL = "https{1}:\/\/(?:\$INSTANCE\$)(?:\/\w+){0,255}(?:\?\w+=\w+){0,1}(?:\&\w+=\w+){0,255}",
    

    OR like below when it’s RegExp instance

    patternCustomTSConfigURL = /https://(?:[$]INSTANCE[$])(?:/w+){0,255}(?:?w+=w+){0,1}(?:&w+=w+){0,255}/,
    

    P.S. it’s nothing to do with Angular, as Angular just concatenate start of the string ^ and end of the string $ matchers to the string if you don’t specify it explicitly

    Angular code Ref: https://github.com/angular/angular/blob/80fe08be96633171567e30eb91dd1d23c60a2952/packages/forms/src/validators.ts#L533

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search