Why can't I replace ":)" [duplicate] - java

This question already has answers here:
How to replace brackets in strings
(4 answers)
Closed 8 years ago.
I can't seem to replace a string of ":)" to something else, here is my code:
if(message.contains(":)")) message = message.replaceAll(":)", replacement);
This is the error:
Exception in thread "Listen" java.util.regex.PatternSyntaxException: Unmatched closing ')'
near index 0
:)
^
What should I do?

Don't use replaceAll(); use replace() when you want to replace literal strings:
message.replace(":)", replacement)
replaceAll() deals with regular expressions, in which ) has a special meaning, hence the error.

You must escape ) in regexen:
message = message.replaceAll(":\\)", replacement);
This is because ) has special meaning (capture groups), so you have to "tell" regex that you just want a literal ).

Write:
message.replaceAll(Pattern.quote(":)"), replacement);
String#replaceAll accept a regex, not a regular String. ) has a special meaning in regex, using quote will cause treating :) as the String :) and not the regex.
If you don't want to use Pattern#quote, you should escape the ) by \\. Note that escaping a regex is done by \, but in Java, \ is written as \\.
If you don't like any of the mentioned, use String#replace that doesn't accept a regex, and you're fine.

Related

How to split a java string with "("? [duplicate]

This question already has answers here:
Groovy/Java split string on parentheses "("
(5 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 3 years ago.
I am trying to split a java string with the character "(".
For example :
split("wer(sde")= "wer"+"sde".
But it give exception. Is there a way to split this string using split() function without changing the character "(" to some other character.
String[] cp=cmd.split("{");
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
The thing is, split() receives as parameter a regular expression. Both {} and () are meta-characters and have a special meaning in a regex, so you need to escape them like this:
String[] cp = cmd.split("\\(|\\)");
The method split of String accept a String, that parameter is a regex :
public String[] split(String regex)
Splits this string around matches of the given regular expression.
Since ( is a reserved character in regex, you need to escape it \(.
But in Java, you need to escape twice \\(, once for the String and the second for the regex
This gives :
s.split("\\(");
Parentheses mean something in RegEx, they're used to group characters together. As such, if you intend to reference the literal character, '(' you must escape it within the RegEx:
String[] cp = cmd.split("\\(");
Note the use of two backslashes. This is because the JVM will also interpret a backslash as a metacharacter for escape purposes, so you must escape the backslash itself with another backslash in order for it to make it into the RegEx.

Replace the $ symbol in String [duplicate]

This question already has answers here:
Java regular expressions and dollar sign
(5 answers)
Closed 3 years ago.
How to replace all "$$$" present in a String?
I tried
story.replaceAll("$$$","\n")
This displays a warning: Anchor $ in unexpected position and the code fails to work. The code takes the "$" symbol as an anchor for a regular expression. I just need to replace that symbol.
Is there any way to do this?
"$" is a special character for regular expressions.
Try the following:
System.out.println(story.replaceAll("\\$\\$\\$", "\n"));
We are escaping the "$" character with a '\' in the above code.
There are several ways you can do this. It depends on what you want to do, and how elegant your solution is:
String replacement = "\n"; // The replacement string
// The first way:
story.replaceAll("[$]{3}", replacement);
// Second way:
story.replaceAll("\\${3}", replacement);
// Third way:
story.replaceAll("\\$\\$\\$", replacement);
You can replace any special characters (Regular Expression-wise) by escaping that character with a backslash. Since Java-literals use the backslash as escaping-character too, you need to escape the backslash itself.
story.replaceAll("\\${3}", something);
By using {3}behind the $, you say, that it should be found exactly three times. Looks a bit more elegant than "\\$\\$\\$".
something is thus your replacement, for example "" or \n, depending on what you want.
this will surely work..
story.replaceAll("\\$\\$\\$","\n")
YOu can do this for any special character.

Why does split(".") fail? java [duplicate]

This question already has answers here:
Java RegEx meta character (.) and ordinary dot?
(9 answers)
Closed 8 years ago.
I've written the following code:
String[] arr = ((String) "asd.asd").split(".");
and arr=[]. Why?
split takes a regular expression as an argument. "." in regular means "any character".
Instead, use:
String[] arr = "asd.asd".split("\\.");
The backslashes escape the special meaning of the "." character in a regular expression.
http://docs.oracle.com/javase/tutorial/essential/regex/
split() accepts a regex. you should escape the . use "\\." . In regex . is a special character (Meta character) which means match any character.
You must double escape the ., otherwise the regular expression represents it as "any character".
Also, you don't need to cast "asd.asd" as String.
String[] arr = "asd.asd".split("\\.");
Because '.' is a special character. You need to escape it by writing it like this '\\.'

In regular expression, how can we match the character "." itself? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
regular expression for DOT
Say I have a String:
String domain = "www.example.com";
To extract the word "example" I am using the split function in java
String[] keys = domain.split(".");
String result = keys[1];
Clearly this is wrong because the "." is a wrong regular expression since it matches any character.
What is the escape sequence which matches specifically the character "."?
Though this question does seem trivial but I can't seem to find any quick reference or previous answers. Thanks.
By escaping it like as follows
\\.
Use \\.. You need to escape it.
You can get the regular expression for any literal string by using Pattern.quote().
Pattern.quote(".") evaluates to "\\."
In this case it would probably be clearer just to use \\.
You can escape . by prefixing it with \\. Hence, use \\. Reason is that the literal string \\ is a single backslash. In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash.
You can escape the . character by using \\. or using the brackets [.].
Hence your code becomes:
String[] keys = domain.split("\\."); // or domain.split("[.]");
String result = keys[1];
Or you could create a class containing the dot, without escaping:
[.]

Java - Escaping Meta-characters [ and ] in Regex [duplicate]

This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
Closed 3 years ago.
I am attempting to replace the first occurrence of the string "[]" in another string:
aString.replaceFirst("[]", "blah");
I get the error:
java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []
[ and ] are obviously metacharacters, however when I try to escape them with a \
eclipse complains that it is not a valid escape sequence.
I've looked but couldn't find, what am I missing?
Thank You
Regex patterns use \ as escape character, but so does Java. So to get a single escape (\) in a regex pattern you should write: \\. To escape an escape inside a regex, double the pattern: \\\\.
Of course that's extremely tedious, made all the worse because regexes have a ton of escape sequences like that. Which is why Java regexes also support “quoting” litteral parts of the pattern and this allows you to write your pattern as: \\Q[]\\E.
EDIT: As the other answer hints at: java.util.regex.Pattern.quote() performs this wrapping between \\Q and \\E.
Try \\[ and \\]. You need to double escape, because \ is also an escape character for strings (as is \" when you want to have double-quotes in your text). Therefore to get a \ in your string you have to use \\.
aString.replaceFirst("\\[\\]", "blah");
or in the more general case
aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");

Categories

Resources