douxi3233 2016-09-09 08:51
浏览 205

使用grep检查用户名

I search a grep command to check usernames like:-

mi.ma
ab-bc
ab.bc-ad
ab_de
mima

Not allowed should be:

..mima
mima..
mia--bc
mia---ad
ab___de
__ab
ab__

Allowed should be a-z, 0-9, -, ., _ but not double -, ., _ and this also not in front or end. And it must min. have 3 characters.

  • 写回答

2条回答 默认 最新

  • dongtidai6519 2016-09-09 08:58
    关注

    Here:

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

    Demo

    Explanation:

    • The first [a-z0-9]+ ensures the user name STARTS with a (lower case) letter or number.
    • [._-]? allows the presence of one (or none) ".", "_" or "-" character.
    • The final [a-z0-9]+ ensures the user name ENDS with a (lower case) letter or number.
    • Wrapping this second group in (...)* allows for multiple ".", "_" or "-" characters in the middle of the user name (so long as they are separated by letters/numbers), e.g. "ab.bc-ad".

    Edit:

    I just noticed your final condition for matching:

    And it must min. have 3 characters.

    The easiest way to add this as part of the regex is with a lookahead - i.e.:

    ^(?=.{3,})[a-z0-9]+(?:[._-]?[a-z0-9]+)*$
    

    Here is an updated demo with additional test strings.

    Edit2:

    The above is perfectly valid for PHP. However, in case anyone reading this is actually looking for an answer using grep (i.e. nothing to do with PHP...)

    First note that you can use the -x modifier to match an exact string, and therefore do away with the ^ and $ anchors. You then have two options to make this work:

    1. Use the above code with grep -P, or equivalently pcregrep, since the standard grep tool does not support lookaheads:

      pcregrep -x "(?=.{3,})[a-z0-9]+([._-]?[a-z0-9]+)*" <filename>
      
    2. Use grep -E, or equivalently egrep, for the special character support; pipe the output through a second grep to satisfy the "min 3 chars" condition:

      egrep -x "[a-z0-9]+([._-]?[a-z0-9]+)*" <filename> | grep ...
      
    评论

报告相同问题?

问题事件

  • 请采纳用户回复 10月17日

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划