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日

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数