91

我正在尝试创建一个正则表达式来根据这些条件验证用户名:

  1. 仅包含字母数字字符、 下划线
  2. 下划线和点不能位于用户名的末尾开头(例如_username/ username_/ .username/ username.)。
  3. 下划线和点不能相邻(例如user_.name)。
  4. 下划线或点不能连续多次使用(例如user__name/ user..name)。
  5. 字符数必须介于 8 到 20 之间。

这就是我到目前为止所做的;听起来它强制执行所有标准规则,但第 5 条规则。我不知道如何将第 5 条规则添加到此:

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

11 回答 11

365
^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
 └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
       │         │         │            │           no _ or . at the end
       │         │         │            │
       │         │         │            allowed characters
       │         │         │
       │         │         no __ or _. or ._ or .. inside
       │         │
       │         no _ or . at the beginning
       │
       username is 8-20 characters long

如果您的浏览器由于缺乏负面的后视支持而引发错误,请使用以下替代模式:

^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$
于 2012-08-18T13:52:40.120 回答
14

尽管我喜欢正则表达式,但我认为可读性是有限的

所以我建议

new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");

它更长,但不需要维护者打开 expresso 即可理解。

当然你可以评论一个很长的正则表达式,但是读过它的人必须依赖信任......

于 2012-08-18T13:45:54.600 回答
13

我想你必须在这里使用 Lookahead 表达式。http://www.regular-expressions.info/lookaround.html

尝试

^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$

[a-zA-Z0-9]一个字母数字的 THEN (

_(?!\.)一个 _ 后不跟一个 . 或者

\.(?!_)一个 。后面没有 _ OR

[a-zA-Z0-9]一个字母数字) FOR

{6,18}最少 6 到最多 18 次 THEN

[a-zA-Z0-9]一个字母数字

(第一个字符是字母数字,然后是 6 到 18 个字符,最后一个字符是字母数字,6+2=8, 18+2=20)

于 2012-08-18T11:51:30.997 回答
8

对菲利普的答案稍作修改修复了最新要求

^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
于 2012-08-18T12:36:28.803 回答
3
private static final Scanner scan = new Scanner(System.in);

public static void main(String[] args) {
    int n = Integer.parseInt(scan.nextLine());
    while (n-- != 0) {
        String userName = scan.nextLine();
        String regularExpression = "^[[A-Z]|[a-z]][[A-Z]|[a-z]|\\d|[_]]{7,29}$";
        if (userName.matches(regularExpression)) {
            System.out.println("Valid");
        } else {
            System.out.println("Invalid");
        }
    }
}
于 2018-10-06T12:12:05.910 回答
3
^(?=.{4,20}$)(?:[a-zA-Z\d]+(?:(?:\.|-|_)[a-zA-Z\d])*)+$

你可以在这里测试正则表达式

于 2019-11-08T17:37:09.383 回答
1

^[a-z0-9_-]{3,15}$

^ # 行首

[a-z0-9_-] # 匹配列表中的字符和符号,az、0-9、下划线、连字符

{3,15} # 长度至少 3 个字符,最大长度 15

$ # 行尾

于 2017-04-17T15:38:01.727 回答
0

这个应该可以解决问题:

if (Regex.IsMatch(text, @"
    # Validate username with 5 constraints.
    ^                          # Anchor to start of string.
    # 1- only contains alphanumeric characters , underscore and dot.
    # 2- underscore and dot can't be at the end or start of username,
    # 3- underscore and dot can't come next to each other.
    # 4- each time just one occurrence of underscore or dot is valid.
    (?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
    # 5- number of characters must be between 8 to 20.
    [A-Za-z0-9_.]{8,20}        # Apply constraint 5.
    $                          # Anchor to end of string.
    ", RegexOptions.IgnorePatternWhitespace))
{
    // Successful match
} else {
    // Match attempt failed
} 
于 2012-08-18T13:40:43.657 回答
0

对不起,我从自己的库中生成了这个,它使用对 Dart/Javascript/Java/Python 有效的语法,但无论如何,这里是:

(?:^)(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789]){1,1})(?!(?:(?:(?:(?:_\.){1,1}))|(?:(?:(?:__){1,1}))|(?:(?:(?:\.\.){1,1}))))(?:(?:(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789._]){1,1})(?!(?:(?:(?:(?:_\.){1,1}))|(?:(?:(?:__){1,1}))|(?:(?:(?:\.\.){1,1}))))){6,18})(?:(?:[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKlMNOPQRSTUVWXYZ0123456789]){1,1})(?:$)

我的图书馆代码:

var alphaNumeric = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "l", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var allValidCharacters = new List.from(alphaNumeric);
allValidCharacters.addAll([".", "_"]);

var invalidSequence = (r) => r
  .eitherString("_.")
  .orString("__")
  .orString("..");

var regex = new RegExpBuilder()
  .start()
  .exactly(1).from(alphaNumeric).notBehind(invalidSequence)
  .min(6).max(18).like((r) => r.exactly(1).from(allValidCharacters).notBehind(invalidSequence))
  .exactly(1).from(alphaNumeric)
  .end()
  .getRegExp();

我的图书馆:https ://github.com/thebinarysearchtree/RegExpBuilder

于 2012-08-18T12:36:18.590 回答
0
const regex = /^moe_(app|lab)[A-Za-z0-9]{3}$/;
const str = `moe_app_baa`;
let m;

if ((m = regex.exec(str)) !== null) {
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
于 2021-10-11T09:48:48.963 回答
-2
function isUserName(val){
    let regUser=/^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/;
    if(!regUser.test(val)){
      return 'Name can only use letters,numbers, minimum length is 8 characters';
    }
  }
于 2020-10-20T17:29:13.440 回答