Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2559442
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-29 14:11:59

这篇文章主要记录怎样使用java api中的java.util.regex.Matcher 和java.util.regex.Pattern

例如,用户名的正则表达式如下:
  1. ^[a-z0-9_-]{3,15}$
上述正则表达式的含义:
  1. ^          # Start of the line
  2. [a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
  3. {3,15}     # Length at least 3 characters and maximum length of 15
  4. $          # End of the line

完整实例

  1. package org.hello.reg;

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

  4. public class UsernameValidator {

  5.     private Pattern pattern;
  6.     private Matcher matcher;
  7.     
  8.     public static void main(String[] args){
  9.         UsernameValidator usernameValidator = new UsernameValidator();
  10.         String[] usernames = new String[6];
  11.         usernames[0] = "hello";
  12.         usernames[1] ="he#llo";
  13.         usernames[2] = "he";
  14.         usernames[3] = "ho_o";
  15.         usernames[4] = "kkkkkkkkkkkkkkkkkkkk";
  16.         usernames[5] = "#####";
  17.         
  18.         for(String name : usernames){
  19.             boolean valid = usernameValidator.validate(name);
  20.             System.out.println("Username is valid: " + name + " , " + valid);
  21.         }
  22.         
  23.     }
  24.     
  25.     private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
  26.     
  27.     public UsernameValidator(){
  28.         pattern = Pattern.compile(USERNAME_PATTERN);
  29.         
  30.     }
  31.     
  32.     public boolean validate(final String username){
  33.         matcher = pattern.matcher(username);
  34.         return matcher.matches();
  35.     }
  36. }
运行结果

  1. Username is valid: hello , true
  2. Username is valid: he#llo , false
  3. Username is valid: he , false
  4. Username is valid: ho_o , true
  5. Username is valid: kkkkkkkkkkkkkkkkkkkk , false
  6. Username is valid: ##### , false

阅读(9915) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~