doucan4815
doucan4815
2019-06-27 21:41
浏览 13
已采纳

字符串模式后字符串的正则表达式

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drr7731
    drr7731 2019-06-27 21:45
    已采纳

    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.
    点赞 评论
  • dongmu5106
    dongmu5106 2019-06-27 21:52
    ^Exactfoobar(?:\.[a-z0-9_\-]+){2}(?:\.[A-Za-z0-9_\-]+)+$
    

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

    点赞 评论

相关推荐