简体   繁体   English

Java正则表达式检查某些字符是否与模式匹配

[英]Java regex check if certain characters match pattern

I need your help with regex. 我需要您的正则表达式帮助。 This is my requirement, check string if it starts with 0937, 937 or 63937. Next check if string ONLY contains digits and check if length of characters for 0937 = 11, 937 = 10, 63937 = 12. 这是我的要求,请检查字符串是否以0937、937或63937开头。接下来检查字符串是否仅包含数字,并检查0937 = 11、937 = 10、63937 = 12的字符长度。

So far this is what I've tried: 到目前为止,这是我尝试过的:

class MyRegex {

static Pattern p1 = Pattern.compile("^0937[0-9]{11}+$");
static Pattern p2 = Pattern.compile("^937[0-9]+{10}$");
static Pattern p3 = Pattern.compile("^63937[0-9]{12}$");

 public static void main(String []args){

    String phone = "09375126435"; //"639375126439"; // "9375126435";

    System.out.println(validateABSMobileNumber(phone));
 }

 public static boolean validateABSMobileNumber(String phone){
    return p1.matcher(phone).matches() || p2.matcher(phone).matches() || p3.matcher(phone).matches() ;
}

}

Sample test cases: 样本测试案例:

09375126435 = true 0937512643 = false 639375126439 = true 63937512643 = false 9375126439 = true 937512643 = false 09375126435 =真0937512643 =真639375126439 =真63937512643 =真9375126439 =真937512643 =真

But it doesn't run correctly. 但是它不能正常运行。 Any ideas how to fix this? 任何想法如何解决这一问题? Thanks. 谢谢。

Your patterns were counting characters incorrectly. 您的模式错误地计算了字符。 Use this: 用这个:

static Pattern p1 = Pattern.compile("^0937[0-9]{7}$");
static Pattern p2 = Pattern.compile("^937[0-9]{7}$");
static Pattern p3 = Pattern.compile("^63937[0-9]{7}$");

I think you can use only one pattern, something like this: 我认为您只能使用一种模式,如下所示:

static Pattern p = Pattern.compile("^((0937)|(937)|(63937))[0-9]{7}$");

This patter include your three cases with the correct length. 此模式包括长度正确的三个案例。 So if you can have a maintable regex, I recommend you to use a properties file. 因此,如果您可以拥有一个主表正则表达式,建议您使用属性文件。

I hope this information helps you. 希望这些信息对您有所帮助。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM