【问题标题】:regex allow only letters, numbers, dot, underscore, dash. at least 5 characters正则表达式只允许字母、数字、点、下划线、破折号。至少 5 个字符
【发布时间】:2016-07-03 03:09:13
【问题描述】:

如何使正则表达式符合规则

  1. 只允许字母(大写或小写)、数字、点、下划线、破折号
  2. 至少 5 个字符
  3. 不能包含通用术语或扩展名(例如:.com、.net)。 .php、.mustache、.html、.js、.jpeg、.jpg、.png、.tiff、..
    例如
    username.comx
    username.commeo

这是我的,如果包含点、下划线、破折号,则无法匹配
以及如何排除扩展字符串
^[a-zA-Z0-9_.-]*\w{5,}$

https://regex101.com/r/pT0iD8/1

【问题讨论】:

  • example.com 可以接受吗?
  • 不包含.com
  • 那么你的第三条规则不清楚..
  • 感谢回复,我更新有问题

标签: javascript regex


【解决方案1】:

应该是这样的:

^([\w.-](?!\.(com|net|html?|js|jpe?g|png)$)){5,}$

解释:

^              # from start            
([\w.-]        # \w is equal to [a-zA-Z0-9_]
    (?!\.          # in front can NOT be a dot followed by
        (com           # com
        |net           # OR net
        |html?         # OR htm or html     # ? means optional match
        |js            # OR js
        |jpe?g         # OR jpg or jpeg
        |png           # OR png
        )$             # block only if it is at the end
    )              # end of the negative lookahead
){5,}          # match at least 5 characters in above conditions
$              # till the end

希望对你有帮助。

【讨论】:

  • 对每个步骤的详细解释和向 OP 展示 \w 的魔力投赞成票
  • 感谢回复,我粘贴到https://regex101.com/r/pT0iD8/3 但是如果username.comme 不能通过
  • 这不是 OP 想要的……example.come 是可以接受的,但 your pattern doesn't match it
  • @user1575921。当我第一次阅读您的问题时,我没有看到第三条规则,对此感到抱歉......我已经更新了
  • @WashingtonGuedes 非常感谢!这行得通!并感谢您的详细解释!
【解决方案2】:

虽然你可以(可能)将它整理成一个正则表达式,但它的性能真的很糟糕......你最好使用一个函数,它可以使用两个 正则表达式。

第二部分最好用数组检查,将所有值拆分成一个数组。

function isValid(str) {
  return (/^([\w\d_\.]{5,})$/i).test(str) 
    && !(/\.(dll|com|net|exe|php|html|js|jpeg|jpg|png|tiff|gif)$/i).test(str);
}

【讨论】:

  • @PM77-1 在 JS 中的前瞻速度特别慢,而且更难理解内联......虽然可以说正则表达式一般很难让人们掌握......另外,检查最后的字符对于常见的扩展名应该与允许的字符检查分开,这实际上是两条规则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
相关资源
最近更新 更多