简体   繁体   中英

Regular expression using string.matches always returning false though i am expecting true

I am trying to find the whether all the case-based characters in the string following the non based-characters. ie Non case-based characters are in upper case and all other case based characters are in lower case

example: What Is Your Test

Regular expression which i have defined is : \\b[AZ]

String alphaCheck="What Is Your Test";
System.out.println(alphaCheck.matches("\b[A-Z]"));

([AZ][az]+(\\\\s+|$))+ will work for you :

public static void main(String[] args) {
    String s = "What Is Your Test";
    System.out.println(s.matches("([A-Z][a-z]+(\\s+|$))+"));

    String s2 = "What is";
    System.out.println(s2.matches("([A-Z][a-z]+(\\s+|$))+"));
}

O/P :

true
false

As another option you could use the negative way, and check if there is any not fitting your criteria:

String alphaCheck="What Is Your Test";
System.out.println(!alphaCheck.matches(".*\\b[a-z]+.*"));
alphaCheck="What Is Your test";
System.out.println(!alphaCheck.matches(".*\\b[a-z]+.*"));
alphaCheck="what Is Your Test";
System.out.println(!alphaCheck.matches(".*\\b[a-z]+.*"));

O/P:

true
false
false

You just have to revert the String#matches return to represent if it´s correct or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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