简体   繁体   中英

regex allow only letters, numbers, dot, underscore, dash. at least 5 characters

How to make regex fit below rules

  1. allow only letters (uppercase or smallcase), numbers, dot, underscore, dash
  2. at least 5 characters
  3. can't contain generic terms or extensions (ex: .com, .net). .php, .mustache, .html, .js, .jpeg, .jpg, .png, .tiff, ..
    eg
    username.com x
    username.comme o

here's mine, fail to match if contain dot, underscore, dash,
and how to exclude extension string
^[a-zA-Z0-9_.-]*\\w{5,}$

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

It would be something like this:

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

Explaining:

^              # 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

Hope it helps.

Though you could (possibly) wrangle it into a single regexp, it would perform really badly... you'd be much better off using a function, that can use two regular expressions.

The second part may be better off with an array check, with all the values split into an array.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM