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

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

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 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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?