dqyin0101 2017-07-24 03:39
浏览 303
已采纳

将Golang正则表达式转换为JS正则表达式

I have a regex from Golang (nameComponentRegexp). How can I convert it to JavaScript style regex?

The main blocking problem for me:

  1. How can I do optional and repeated in JavaScript correctly
  2. I tried copy from match(`(?:[._]|__|[-]*)`) but it cannot match single period or single underscore. I tried it from online regex tester.

The description from Golang:

nameComponentRegexp restricts registry path component names to start with at least one letter or number, with following parts able to be separated by one period, one or two underscore and multiple dashes.

alphaNumericRegexp = match(`[a-z0-9]+`)
separatorRegexp = match(`(?:[._]|__|[-]*)`)

nameComponentRegexp = expression(
    alphaNumericRegexp,
    optional(repeated(separatorRegexp, alphaNumericRegexp)))

Some valid example:

  • a.a
  • a_a
  • a__a
  • a-a
  • a--a
  • a---a
  • 写回答

1条回答 默认 最新

  • dps123456789 2017-07-24 06:41
    关注

    See how you build the nameComponentRegexp: you start with alphaNumericRegexp and then match 1 or 0 occurrences of 1 or more sequences of separatorRegexp+alphaNumericRegexp.

    optional() does the following:

    // optional wraps the expression in a non-capturing group and makes the
    // production optional.

    func optional(res ...*regexp.Regexp) *regexp.Regexp {
      return match(group(expression(res...)).String() + `?`)
    }

    repeated() does this:

    // repeated wraps the regexp in a non-capturing group to get one or more
    // matches.

    func repeated(res ...*regexp.Regexp) *regexp.Regexp {
      return match(group(expression(res...)).String() + `+`)
    }

    Thus, what you need is

    /^[a-z0-9]+(?:(?:[._]|__|-*)[a-z0-9]+)*$/
    

    See the regex demo

    Details:

    • ^ - start of string
    • [a-z0-9]+ - 1 or more alphanumeric symbols
    • (?:(?:[._]|__|-*)[a-z0-9]+)* - zero or more sequences of:
      • (?:[._]|__|-*) - a ., _, __, or 0+ hyphens
      • [a-z0-9]+- 1 or more alphanumeric symbols

    If you want to disallow strings like aaaa, you need to replace all * in the pattern (2 occurrences) with + (demo).

    JS demo:

    var ss = ['a.a','a_a','a__a','a-a','a--a','a---a'];
    var rx = /^[a-z0-9]+(?:(?:[._]|__|-*)[a-z0-9]+)*$/;
    for (var s of ss) {
     console.log(s,"=>", rx.test(s));
    }

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,