我尝试使用 matches("regex") 抛出异常,但总是出错。有没有办法匹配标题中的模式?例如,模式应为“s98340”或“s12345”。开头只有一个字符,后跟任意 5 位数字。 捕获异常:
try{
if(originalLocation.length() != 6 && originalLocation.matches("s[0-9]{5}"))
throw new IllegalOriginalLocationException("Original Location is invalid.");
}
catch(IllegalOriginalLocationException ex){
System.out.println(ex);
}
当我设置 String sr = "s4a234"时,未捕获异常。
最佳答案
当您通过s98340
时就像您的方法的字符串一样, originalLocation.length() != 6
条件返回 false,因此,您得到当前的行为。
由于正则表达式已经匹配仅 6 个字符的字符串,因此足以删除该条件:
try {
if(originalLocation.matches("s[0-9]{5}"))
throw new IllegalOriginalLocationException("Original Location is invalid.");
}
catch(IllegalOriginalLocationException ex) {
System.out.println(ex);
}
originalLocation.matches("s[0-9]{5}")
行确保字符串以 s
开头然后正好有 5 个 ASCII 数字。请记住 .matches()
里面的模式默认情况下锚定在字符串的开头和结尾。
关于java 正则表达式 : finding a pattern of one character s follows by 5 digits range 0-9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221861/