woky
woky

Reputation: 4936

Java, regular expressions, String#matches(String)

I'm used to regular expressions from Perl. Does anybody know why this doesn't work (eg. "yea" isn't printed)?

if ("zip".matches("ip"))
  System.out.println("yea");

Thank you.

Upvotes: 0

Views: 155

Answers (4)

Brian Roach
Brian Roach

Reputation: 76898

matches() is a complete match; the string has to match the pattern.

if ("zip".matches("zip"))
    System.out.println("yea");

So you could do:

if ("zip".matches(".*ip"))
  System.out.println("yea");

For partial matching you can use the complete regex classes and the find() method;

Pattern p = Pattern.compile("ip");
Matcher m = p.matcher("zip");
if (m.find())
    System.out.println("yea");

Upvotes: 4

RichW
RichW

Reputation: 2024

The argument to matches() needs to be a fully-formed regular expression rather than just a substring. Either of the following expressions would cause "yea" to be printed:

"zip".matches(".*ip.*")

"zip".matches("zip")

Upvotes: 1

Vaandu
Vaandu

Reputation: 4935

Try endsWith instead of matches for your "zip" case.

"zip".endsWith("ip");

If you need regex,

"zip".matches(".*ip");

http://www.exampledepot.com/egs/java.lang/HasSubstr.html

Upvotes: 0

Joan Wilkinson
Joan Wilkinson

Reputation: 143

Use:

if ("zip".contains("ip"))

instead of a RegEx in this case. It's faster, since no RegEx-parser is needed.

Upvotes: 0

Related Questions