1

I am trying to find create a pattern that would satisfy below rules

mydomain.com
www.mydomain.com
www.alternatedomain.com
www100.mydomain.com
online.mydomain.com
subl.mydomain.com

The pattern that i have created so far doesnt work.

I may or may not have values before mydomain.

private static final String MY_PATTERN =
 "((www*|online|subl)*\\.((mydomain|alternatedomain)\\.(com)$))";

And if it has values it should belong to a restrictive set

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
oxygenan
  • 1,023
  • 2
  • 12
  • 21
  • Check https://regex101.com/r/d0Ya7B/1 – Wiktor Stribiżew Dec 18 '18 at 14:41
  • Thank you !! I should have replied earlier. Though this works i have a query on the initial part of the regex why do we need ?: in the first part of the check. The regex seems to be returning results even without that ?:. – oxygenan Feb 07 '19 at 07:57
  • Why do you capture the parts of the string? Are you using them later? If not, use *non-capturing groups*, `(?:...)`. – Wiktor Stribiżew Feb 07 '19 at 08:00

2 Answers2

2

I suggest using

String rx = "^(?:(?:www\\d*|online|subl)*\\.)?(?:mydomain|alternatedomain)\\.com$";

See the regex demo

I removed or converted to non-capturing groups all capturing groups in the pattern. If you are using those parts of the string later, revert them.

If you use the regex with .matches() method remove ^ and $, they are redundant then, as the method makes sure the entire string matches the pattern.

Details

  • ^ - start of string
  • (?:(?:www\\d*|online|subl)*\\.)? - an optional non-capturing group matching
    • (?:www\\d*|online|subl)* - www and 0+ digits, or online or subl
    • \\. - a dot
  • (?:mydomain|alternatedomain) - a non-capturing group matching either mydomain or alternatedomain
  • \\.com - .com substring
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Try ((www\\d*|online|subl)\\.)?(mydomain|alternatedomain)\\.com

You can test your regex online here but don't forget to replace the \\ with a single \ (because in Java code \\ means a \ in regex)

aBnormaLz
  • 809
  • 6
  • 22