0

I have a string like this (4 words separated by dot)

Exactfoobar.foobar-_nocaps.foobar-_nocaps.foobar-_caps

I need to write a regex to find the pattern as above.

  1. There could be 4 or more fields separated by a dot
  2. The first word should be exactly Exactfoobar.
  3. The 2nd and 3rd word can't have caps but can have -_
  4. The 4th word and so on can have caps with -_

I was thinking of using groups but its not working here:

^Exactfoobar\.([a-z0-9][a-z0-9_\-.])+([a-z0-9][a-zA-Z0-9_\-.])+$

How should I think about matching a string after another string. Is it possible?

Trying this in golang but cant seem to get the above regex right

package main

import (
    "fmt"
    "regexp"
)

func main() {

    var validID = regexp.MustCompile(`^ Exactfoobar\.([a-z0-9][a-z0-9_\-.])+([a-z0-9][a-z0-9_\-.])+$`)

    fmt.Println(validID.MatchString("Exactfoobar.somestring.some_other-string.someStringwithCaps"))


}

Result:

false

Thanks

Sumitk
  • 1,485
  • 6
  • 19
  • 31
  • 1
    why not split on the dot character then discard the first element (since it would always be `Exactfoobar`)? That way you don't need regex, which should be a lot faster and more readable. – Olian04 Jun 27 '19 at 21:46

2 Answers2

1

You may use

^Exactfoobar(?:\.[a-z0-9][a-z0-9_-]*){2}(?:\.[a-zA-Z0-9][a-zA-Z0-9_-]*)+$

See the regex demo

  • ^ - Start of string
  • Exactfoobar - some word
  • (?:\.[a-z0-9][a-z0-9_-]*){2} - two repetitions of a ., then a lowercase letter or digit and then 0+ lowercase letters or digits, _ or -
  • (?:\.[a-zA-Z0-9][a-zA-Z0-9_-]*)+ - 1 or more repetitions of
    • \. - dot
    • [a-zA-Z0-9] - a letter or digit
    • [a-zA-Z0-9_-]* - 0+ letters, digits or _ or -
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0
^Exactfoobar(?:\.[a-z0-9_\-]+){2}(?:\.[A-Za-z0-9_\-]+)+$

https://regex101.com/r/PJ9V0L/1

danielb
  • 878
  • 4
  • 10
  • 26