MAG
MAG

Reputation: 3075

java regex sometimes fails to match

I am trying to understand working of regex matching in java and have a doubt in the followeing code snippet

When i run it :http://ideone.com/2vIK77

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {


         String a = "Basic";
         String b = "Bas*";

         boolean matches = Pattern.matches(b, a); 
         System.out.println("1) "+matches);


        String text2    =
        "This is the text to be searched " +
        "for occurrences of the pattern.";

        String pattern2 = ".*is.*";

        boolean matches2 = Pattern.matches(pattern2, text2);

        System.out.println("matches2 = " + matches2);


    }
}

it says false on first and true on second .

1) false
matches2 = true

I am not able to understand why am i getting false in first case .. I expect it to be true . Can someone please suggest me something

Upvotes: 0

Views: 497

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234795

The first pattern: "Bas*", will match any string that starts with "Ba" and then consists of zero or more s characters ("Ba", "Bas", "Bass", etc.). This fails to match "Basic" because "Basic" does not conform to that pattern.

The second pattern, ".*is.*", uses the wild card character ., which means "match any character". It will match any text that has the string "is" anywhere in it, preceded and/or followed by zero or more other characters.

The docs for Pattern has a detailed description of all the special elements that can appear in a pattern.

Upvotes: 5

justhalf
justhalf

Reputation: 9107

You made a typo in b variable, what you want is Bas.* instead of Bas*

Upvotes: 0

Nicole
Nicole

Reputation: 33197

That is because * means "zero or more of the previous character", which was "s".

The docs for matches say:

Attempts to match the entire input sequence against the pattern.

Returns:
true if, and only if, the entire input sequence matches this matcher's pattern

So, "Bas*" only describes the first part of your input text, not the whole text. If you change the pattern to "Bas.*" (the dot character means "any character") then it will match because it will be saying:

"B" then "a" then "s" then any number of anything (.*) 

Upvotes: 1

Related Questions