简体   繁体   中英

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.

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");

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")

Use:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM