duancheng7743 2019-04-04 02:45
浏览 7
已采纳

如何转换使用Lookahead的正则表达式模式?

I'm having trouble converting this regex to something Golang supports. Could I get some help? It's originally from this SO question.

^(?=.{1,24}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$

Here's the criteria:

  1. Only contains alphanumeric characters, underscore and dot.
  2. Underscore and dot can't be at the end or start of a username (e.g _username / username_ / .username / username.).
  3. Underscore and dot can't be next to each other (e.g user_.name).
  4. Underscore or dot can't be used multiple times in a row (e.g user__name / user..name).
  • 写回答

1条回答 默认 最新

  • doukuang8166 2019-04-04 03:31
    关注

    I don't have any experience with Go, so perhaps someone could come up with a better solution.
    Here are the two options I found:

    1. Write a regex that covers everything except the length restriction

    You can use something like this:

    ^(?:[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+)+$
    

    Regex101 demo.

    And you can use len to check for the string length. Here's a full example:

    func main() { 
        var re = regexp.MustCompile(`(?m)^(?:[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+)+$`)
        var str = `username
    user_name
    user.name
    user.name_123
    username$$$
    _username
    username_
    user_.name
    user._name
    user__name
    user..name
    VeryLongUserNameThatExceedsTheLimit
    `
        for i, match := range re.FindAllString(str, -1) {
            if len(match) <= 24 {fmt.Println(match, "found at index", i)}
        }
    }
    

    Output:

    username found at index 0
    user_name found at index 1
    user.name found at index 2
    user.name_123 found at index 3
    

    Test it online.


    2. Use a third-party engine

    I found this .NET-based engine which should support Lookarounds. If the previous solution doesn't work for you, you may look into this. Note that the author of that engine recommends using the built-in engine whenever possible:

    You'll likely be better off with the RE2 engine from the regexp package and should only use this if you need to write very complex patterns or require compatibility with .NET.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。