Robert O'Neal
Robert O'Neal

Reputation: 43

How can I add optional strings in my regex matcher?

My regex: https?://iam(.*).foo.com/v1/bar

which works but I want the middle part to be more specific instead of just allowing anything. For example, these URLs should all match:

https://iam.dev.foo.com/v1/bar
https://iam.uat.foo.com/v1/bar
https://iam.foo.com/v1/bar

Is this possible through regular expressions?

Upvotes: 1

Views: 38

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You can use

https?://iam(?:\.(?:dev|uat))?\.foo\.com/v1/bar

See the regex demo.

Details:

  • https?:// - http:// or https://
  • iam - a literal iam string
  • (?:\.(?:dev|uat))? - an optional non-capturing group matching
    • \. - a dot char
    • (?:dev|uat) - either dev or uat string
  • \.foo\.com/v1/bar - a literal .foo.com/v1/bar string. Note that dots are special regex metacharacters and must be escaped if literal dots are meant.

Upvotes: 1

Related Questions