如何使用正则表达式验证用户名

  • Post author:
  • Post category:其他


用户名正则表达式模式

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

描述

^                    # Start of the line
  [a-z0-9_-]	     # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
             {3,15}  # Length at least 3 characters and maximum length of 15 
$                    # End of the line

整个组合是指3到15个字符,只能包含小写字符,数字或特殊符号“ _-”。 这是在不同网站中广泛使用的常见用户名模式。

1. Java正则表达式示例

UsernameValidator.java
package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UsernameValidator{
	
	  private Pattern pattern;
	  private Matcher matcher;
 
	  private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
	  
	  public UsernameValidator()