Java的正则表达式怎么验证一个数在0-493和500的数字
[code="java"]
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static String modify(int numb){
if(numb<10)
return "00"+numb;
else if (numb <100)
return "0"+numb;
else
return ""+numb;
}
public static void isInRange(int numb){
String str = Test.modify(numb);
Matcher m1 = Pattern.compile("^[0-4][0-9][0-9]$").matcher(str);
Matcher m2 = Pattern.compile("^500$").matcher(str);
Matcher m3 = Pattern.compile("^49[4-9]$").matcher(str);
if( m1.matches()){
if(!m3.matches()){
System.out.println(str+"匹配");
}
}else if(m2.matches()){
System.out.println(str+"匹配");
}
}
public static void main(String[] args) {
Test.isInRange(2);
Test.isInRange(23);
Test.isInRange(279);
Test.isInRange(499);
Test.isInRange(500);
Test.isInRange(502);
}
}
[/code]
[b][color=blue]你试试[/color][/b]
[color=blue]思路:
1、首先将数字拓展到3位的字符串。
如 97 --> 097 167 --> 167
2、然后配置字符串。
首位[0-4][0-9][0-9]或则 500
[/color]
[color=blue]到最后的输出,这样会更好:
System.out.println(Integer.valueOf(str)+"匹配");
[/color]