user4822607
user4822607

Reputation:

How to use Caret and dollar in regex Expression?

I'm trying to learn regex but i'm struck at my first code only. I read that caret(^) and dollar($) is used to match at the beginning and end of the test respectively. But i'm getting hard time to figure out what is wrong with my code.

  public class Test1 {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String letterA="cat will die";
            String pattern="[^cat]";
            System.out.println(letterA.matches(pattern));
            String pattern1="^(cat)";
            System.out.println(letterA.matches(pattern1));
            String letterB="Lending your cat";
            String pattern3="[cat$]";
            System.out.println(letterB.matches(pattern3));
            String pattern4="cat$";
            System.out.println(letterB.matches(pattern4));
        }

    }

Every syso is giving me Output false

Upvotes: 1

Views: 6094

Answers (5)

Rodrigo López
Rodrigo López

Reputation: 4259

Caret and dollar are Anchors that just tells if your pattern should look for start(Caret) and end(Dollar) of the line.

Also, inside of brackets, this syntax is changed. if you start with [^...] it means a negation, that you are trying to match any char that is not after the caret. And $ inside the brackets just tells the engine that you are looking for a match for the $ char.

Also, matches in java only return true if you match your entire string.

Having this things in mind, lets pass for each of your cases and see why they are not matching:


String letterA="cat will die";
String pattern="[^cat]";

This regex is looking for a single char that is not 'c' or 'a' or 't'. A string like "f" would return true for this one.


System.out.println(letterA.matches(pattern));
String pattern1="^(cat)";

The () are capturing groups, they do nothing in you case for matching. ^ just tells you will look for the match in the start of the string, and your regex is trying to match the string "cat". This is the only possible match that returns true for this case.


String letterB="Lending your cat";
String pattern3="[cat$]";

This is just trying to match single char strings that would be either 'c' or 'a' or 't' or '$'

and finally :

String pattern4="cat$";

Is just trying to match the exactly string 'cat' (anchored to the end, but it really doesn't make a difference).

So, back to your problem, you need to use something like the .* operator that matches any number of chars like:

  • ^cat.*$ (if you want a string that starts with cat)
  • ^.*cat$ (if you want a string that ends with cat)
  • ^.*cat.*$ (if you want any string that has the text cat in it)

Upvotes: 9

Ankur Anand
Ankur Anand

Reputation: 3904

According to java docs

public boolean matches() Attempts to match the entire region against the pattern.

If the match succeeds then more information can be obtained via the start, end, and group methods.

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

Now Since every one has already mentioned the flaws in your regex. i will not write about about it. But let me give some insight about caret(^) and dollars($)

Reading ^$ and ^

  1. ^ literally matches if the line has beginning of line. `Effectively Speaking meaningless ! Why because every line has a beginning, everyline will match- even the lines that are empty !

see the below code

String letterA="";//i'm not writing anything because matches attempt to match entire region
        String pattern="^";
        System.out.println(letterA.matches(pattern));

It will Give you Output True

So does every line has ending too

String letterA="";
        String pattern="$";
        System.out.println(letterA.matches(pattern));

this will also give you output true

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Actually in Java matches() method matches the entire string. So, using ^ and $ is unnecessary.

You have to use something like this : letterA.matches("cat.*") to match a string which strats with "cat".

Boundary Matcher : matches "word boundaries" denoted by "\\b"

example String : "catterpillar will die";

letterA.matches("cat.*") // will return true

letterA.matches("\\bcat\\b.*")//will return false

Upvotes: 0

Eldar
Eldar

Reputation: 104

That is eample using regex for partial matching.

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class HelloWorld{

     public static void main(String []args){
        Console console = System.console();
        String letterA="cat will die";

            String spattern=".*cat.*";
            System.out.println(letterA.matches(spattern));

            Pattern pattern = 
            Pattern.compile(console.readLine("%nEnter your regex: "));
            Matcher matcher = 
            pattern.matcher(console.readLine("Enter input string to search: "));

            System.out.println(matcher.find());
     }
}

Upvotes: 0

Tommy
Tommy

Reputation: 620

Read the docs on String.matches. The expression must match fully. For example, try the pattern .*cat.*

Also, ^ used in [] means to negate, so [^cat] reads to a regex engine - "not c, or a, or t". Not sure if you knew, so just in case...

Upvotes: 0

Related Questions