Thursday 19 June 2014

matches (String regex)

public boolean matches(String regex)
Return true if, and only if, this string matches the given regular expression.

class StringMatch{
 public static void main(String args[]){  
  String s1 = "ab";
  String s2 = "aab";
  String s3 = "aaab";
  String s4 = "abcd";
  
  System.out.println(s1.matches("a(.*)b"));
  System.out.println(s2.matches("a(.*)b"));
  System.out.println(s3.matches("a(.*)b"));
  System.out.println(s4.matches("a(.*)b"));
 }
}

Output
true
true
true
false

1. Throws PatternSyntaxException if the regular expression's syntax is invalid.

class StringMatchPatternException{
 public static void main(String args[]){
  String regEx = "a(*)b";
  String s1 = "ab";
  System.out.println(s1.matches(regEx));
 }
}

Output
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta
 character '*' near index 2
a(*)b
  ^
        at java.util.regex.Pattern.error(Pattern.java:1955)
        at java.util.regex.Pattern.sequence(Pattern.java:2123)
        at java.util.regex.Pattern.expr(Pattern.java:1996)
        at java.util.regex.Pattern.group0(Pattern.java:2905)
        at java.util.regex.Pattern.sequence(Pattern.java:2051)
        at java.util.regex.Pattern.expr(Pattern.java:1996)
        at java.util.regex.Pattern.compile(Pattern.java:1696)
        at java.util.regex.Pattern.<init>(Pattern.java:1351)
        at java.util.regex.Pattern.compile(Pattern.java:1028)
        at java.util.regex.Pattern.matches(Pattern.java:1133)
        at java.lang.String.matches(String.java:2108)
        at StringMatchPatternException.main(StringMatchPatternException.java:5)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment