开发者

Java, regular expressions, String#matches(String)

开发者 https://www.devze.com 2023-04-08 09:06 出处:网络
I\'m used to regular expressions from Perl. Does anybody know why this doesn\'t work (eg. \"yea\" isn\'t printed)?

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.pri开发者_如何学Pythonntln("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

0

精彩评论

暂无评论...
验证码 换一张
取 消