2

I would like to have a regex that matches the following domains:

  • dev.api.company.com
  • live.api.company.com
  • test1.dev-api.company.com
  • test2.live-api.company.com
  • yyy.XXXapi.company.com

But does not match on the followings:

  • dev-api.company.com
  • live-api.company.com
  • api.company.com
  • XXXapi.company.com

I have tried this: ^[a-z]+.[a-z-]*api.company.com$ but it not working, and I can not make it work. Can you help me please?

I am using javascript String.match() function.

Rajaswami
  • 171
  • 1
  • 1
  • 7

3 Answers3

3

Try the following regex:

^[a-zA-Z0-9]+\.[^\.]*api\.company\.com$

Demo

razz
  • 9,770
  • 7
  • 50
  • 68
1

Consider the following:

if (string.matches("^(dev\\.api|live\\.api|test\\d+)\\..*$")) {
    // Accepted subdomain
} else {
    // Nope
}

You can enter as many options as you want, separating them with |

Breakup of the regex:

^ - starts with

(option1|option2|option3) - a list of accepted subdomains

\. - a subdomain must be followed by a period

.*$ anything else until the end of the string

This solution allows you to administer the accepted subdomains easily if you don't have a general rule of thumb for selection.

Adrian B.
  • 1,592
  • 1
  • 20
  • 38
  • Thank you, but dev and live are just example. they can be anyhting. not just dev or live it should match devxxx.api.company.com too. But not on devxxx-api.company.com – Rajaswami Mar 07 '16 at 13:55
  • without a rule for the accepted domains, we can't realy make a rule to select anything... – Adrian B. Mar 07 '16 at 13:56
0

Try this:

/^[a-z\\.\\-]{0,}api.company.com$/

Tests against your examples and it works.

twernt
  • 20,271
  • 5
  • 32
  • 41
shiroma
  • 65
  • 1
  • 4