Saturday 21 June 2014

replaceAll (String regex, String replacement)

public String replaceAll(String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.

class StringReplaceAll{
 public static void main(String args[]){
  String s1 = "aab Krishna";
  String s2;
  
  s2 = s1.replaceAll("a(.*)b", "Hi");
  
  System.out.println("s1 = " + s1);
  System.out.println("s2 = " + s2);
 }
}

Output
s1 = aab Krishna
s2 = Hi Krishna

1. Throws PatternSyntaxException if the regular expression's syntax is invalid
class StringReplaceAllPatternSyntax{
 public static void main(String args[]){
  String s1 = "aab Krishna";
  String s2;
  
  s2 = s1.replaceAll("a(*)b", "Hi");
  
  System.out.println("s1 = " + s1);
  System.out.println("s2 = " + s2);
 }
}

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.lang.String.replaceAll(String.java:2210)
        at StringReplaceAllPatternSyntax.main(StringReplaceAllPatternSyntax.java:6)






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment