wood burning stoves 2.0*
The moose likes Java in General and the fly likes new to regex, pattern behavior question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "new to regex, pattern behavior question" Watch "new to regex, pattern behavior question" New topic
Author

new to regex, pattern behavior question

Julia Reynolds
Ranch Hand

Joined: May 31, 2001
Posts: 123
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

Joined: Oct 30, 2001
Posts: 1970
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).


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Julia Reynolds
Ranch Hand

Joined: May 31, 2001
Posts: 123
Peter,

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

Julia
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
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.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Julia Reynolds
Ranch Hand

Joined: May 31, 2001
Posts: 123
Dirk -

Thanks, good advice.

J
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: new to regex, pattern behavior question
 
Similar Threads
String replaceAll()
If only one vowel is entered in the string, then that vowel should be diplayed on console
IDE's for Redhat 6.2 ?
Regex in Java: finding expression 1, but not if it's part of expression 2
Making strings safe for regex