Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is String.matches returning false in Java?

Tags:

java

regex

if("test%$@*)$(%".matches("[^a-zA-Z\\.]"))
    System.exit(0);

if("te/st.txt".matches("[^a-zA-Z\\.]"))
    System.exit(0);

The program isn't exiting even though the regexes should be returning true. What's wrong with the code?

like image 337
Leo Jiang Avatar asked Nov 23 '13 17:11

Leo Jiang


People also ask

How do you match a string in Java?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

How does string matches work in Java?

Variant 1: String matches()This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern.

What is. matches Java?

Java String matches() The matches() method checks whether the string matches the given regular expression or not.


1 Answers

matches returns true only if regex matches entire string. In your case your regex represents only one character that is not a-z, A-Z or ..

I suspect that you want to check if string contains one of these special characters which you described in regex. In that case surround your regex with .* to let regex match entire string. Oh, and you don't have to escape . inside character class [.].

if ("test%$@*)$(%".matches(".*[^a-zA-Z.].*")) {
    //string contains character that is not in rage a-z, A-Z, or '.'

BUT if you care about performance you can use Matcher#find() method which

  1. can return true the moment it will find substring containing match for regex. This way application will not need to check rest of the text, which saves us more time the longer remaining text is.

  2. Will not force us to constantly build Pattern object each time String#matches(regex) is called, because we can create Pattern once and reuse it with different data.

Demo:

Pattern p = Pattern.compile("[^a-zA-Z\\.]");

Matcher m = p.matcher("test%$@*)$(%");
if(m.find())
    System.exit(0);

//OR with Matcher inlined since we don't really need that variable
if (p.matcher("test%$@*)$(%").find())
    System.exit(0);
like image 171
Pshemo Avatar answered Oct 15 '22 18:10

Pshemo