0

I want to match the last character "c". What am I doing wrong? In the documentation it's clearly explained that $ matches the end of the line, i have used regex milions of time on unix shell ecc... and always worked as expected but in java no.

        String string = "abc";
        if(string.matches("c$")){//I know that .*c$ will work.
            System.out.println("yes");//This is never printed
        }

Where is the error? I know that .*c$ will work, but by reading the javadoc I can't find this information. Can some one tell me how do I interpret what is the meaning of this java official tutorial? https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html

or this?

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum

Am I not able to read? Because it seems pretty obvious, but I really can't find the solution, I fell really retarded in this moment!

Under java.lang.String there is a method who clearly say the following: matches(String regex) Tells whether or not this string matches the given regular expression.

Kevin
  • 11
  • 1
  • 4
    `string.matches` only returns true if the pattern matches the whole string. See docs for [`Matcher.matches()`](https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#matches--) which `string.matches` uses. – khelwood Mar 06 '20 at 09:43
  • I know i could use .*c$, but if the doc says "$ matches the end of the line" why should i also put other stuff? This docs are really frustrating. – Kevin Mar 06 '20 at 09:47
  • Java regex distinguishes _matching_ a string with a pattern and _searching_ a string for a pattern. You can search a string for a pattern with something like `Pattern.compile(...).matcher(...).find()`. – khelwood Mar 06 '20 at 09:50
  • this regexp seem to work: string.matches(".*c$") – sab Mar 06 '20 at 10:43

1 Answers1

0

This will print YES.

String line = "abc";
Pattern pattern = Pattern.compile("c$");
Matcher matcher = pattern.matcher(line);

System.out.println(matcher.find() ? "YES" : "NO");
wpnpeiris
  • 766
  • 4
  • 14