• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

new to regex, pattern behavior question

 
Julia Reynolds
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How come this regex pattern comparison returns false?

Pattern pt = Pattern.compile("CDE");
System.out.println("Pattern.matches(\"CDE\", \"ABCDEFGH\"):" + pt.matcher("ABCDEFGH").matches() );

I don't understand why I don't get a match on 'CDE'.

Julia
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your regular expression only matches exactly "CDE", not strings containing "CDE". If you want the latter, I think your expression should be ".*CDE.*" . That is, zero or more characters (of any type), followed by "CDE", followed by zero or more characters (of any type).
 
Julia Reynolds
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Peter,

Aha! You're right, of course. Thanks!

Julia
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Julia, you might also like to take a look at other methods in the regex API.

Pattern pt = Pattern.compile("CDE");
System.out.println("Pattern.matches(\"CDE\", \"ABCDEFGH\"):" + pt.matcher("ABCDEFGH").find() );

In this case, the result is true.
 
Julia Reynolds
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirk -

Thanks, good advice.

J
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic