replaceall() doubt
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Check this simple code :
This simple code as expected gives an O/P of Hello@World
But consider the following code:
The o/p is
@@@@@@@@@@@
Some one please explain this unusual behaviour
SCJP 5.0 77%
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Got this from javadocs
replaceAll
public String replaceAll(String regex,
String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
In ur case, u r doing
"." regular expression matches "anything" so it replaces all characters with "@".
-Vinayak
"I can resist everything except temptation"
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Replaces each substring of this string that matches the given regular expression with the given replacement.
And the "." represents:
Any character (may or may not match line terminators)
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
So, "Hello.World".replaceAll(".","@"); means replace all characters in the string with @.
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
O/P:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at Me.main(Me.java:11)
SCJP 5.0 77%
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
gives me an output of Hello@World
I think it has to do something with the foll , though I am not sure how.
From javadocs
Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.
"I can resist everything except temptation"
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
| Put a gun against his head, pulled my trigger, now he's dead, that tiny ad sure bled The new gardening playing cards kickstarter is now live! https://www.kickstarter.com/projects/paulwheaton/garden-cards |








