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

将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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?