最近在用java开发一个注册模块,里面的密码策略涉及到了正则表达式,于是我就按照QQ帐号注册的密码策略用正则表达式去实现字符的过滤,QQ帐号注册的密码策略如下图:
密码策略涉及到了三个要求,我们就用正则表达式一个一个地来实现,最终用代码进行逻辑与运算就可以了。
长度为6-16个字符:.{6,16}
不能包含空格:\\S*
不能是9位以下纯数字:(.*\\D.*){1,8}|.{9,}
代码如下:
public classRegexp {
public boolean matchs(String str) {
if (str.matches(".{6,16}")&& str.matches("\\S*")
&&str.matches("(.*\\D.*){1,8}|.{9,}"))
return true;
else
return false;
}
}
下面用Junit写些测试用例来测试一下:
import staticorg.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public classRegexpTest {
private static Regexp regexp=new Regexp();
private String param;
private boolean result;
public RegexpTest(Stringparam,booleanresult){
this.param=param;
this.result=result;
}
@Parameters
public staticCollection<Object[]> data(){
return Arrays.asList(new Object[][]{
{"1234a",false},
{"1234567890123456a",false},
{"12 345a",false},
{"12345678",false},
{"123456789",true},
{"12345a",true},
});
}
@Test
public void test() {
assertEquals(regexp.matchs(param),result);
}
}
测试结果:
从测试结果可以看到,6条测试用例全部执行成功!这证明所写的正则表达式满足了我们的需求。