Java的String.matches不区分⼤⼩写正则表达式匹配⽰例需求:输⼊的cmd符合create,listall,delete三种形式,不⽤区分⼤⼩写
写成函数:
public static boolean isAllowed3Cmd(String cmd) {
return cmd.matches("^(?i)(create|delete|listall)$");
}
正则式分析:
^...$:从字符串头到尾全部符合模式
i:不区分⼤⼩写
create|delete|listall:三选⼀
完整测试代码:
public class StringMatchesTest {正则匹配的含义
public static void main(String[] args) {
String[] arr= {"creat","create","Create","DELETE","LISTall","list","creat","del","listalllistall","deletecreate"};
for(String cmd:arr) {
System.out.println(String.format("String:%s %s pattern:%s",cmd,isAllowed3Cmd(cmd)?"matches":"dosen't match","'^(?i)(create|delete|listall)$'"));
}
}
public static boolean isAllowed3Cmd(String cmd) {
return cmd.matches("^(?i)(create|delete|listall)$");
}
}
输出:
String:creat dosen't match pattern:'^(?i)(create|delete|listall)$'
String:create matches pattern:'^(?i)(create|delete|listall)$'
String:Create matches pattern:'^(?i)(create|delete|listall)$'
String:DELETE matches pattern:'^(?i)(create|delete|listall)$'
String:LISTall matches pattern:'^(?i)(create|delete|listall)$'
String:list dosen't match pattern:'^(?i)(create|delete|listall)$'
String:creat dosen't match pattern:'^(?i)(create|delete|listall)$'
String:del dosen't match pattern:'^(?i)(create|delete|listall)$'
String:listalllistall dosen't match pattern:'^(?i)(create|delete|listall)$'
String:deletecreate dosen't match pattern:'^(?i)(create|delete|listall)$'
--2020年3⽉30⽇--
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论