0

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

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 (.*) 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.