how to replace a string in Java - java

I have a question about using replaceAll() function.
if a string has parentheses as a pair, replace it with "",
while(S.contains("()"))
{
S = S.replaceAll("\\(\\)", "");
}
but why in replaceAll("\\(\\)", "");need to use \\(\\)?

Because as noted by the javadocs, the argument is a regular expression.
Parenthesis in a regular expression are used for grouping. If you're going to match parenthesis as part of a regular expression they must be escaped.

It's because replaceAll expects a regex and ( and ) have a special meaning in a regex expressions and need to be escaped.
An alternative is to use replace, which counter-intuitively does the same thing as replaceAll but takes a string as an input instead of a regex:
S = S.replace("()", "");

First, your code can be replaced with:
S = S.replace("()", "");
without the while loop.
Second, the first argument to .replaceAll() is a regular expression, and parens are special tokens in regular expressions (they are grouping operators).
And also, .replaceAll() replaces all occurrences, so you didn't even need the while loop here. Starting with Java 6 you could also have written:
S = S.replaceAll("\\Q()\\E", "");
It is let as an exercise to the reader as to what \Q and \E are: http://regularexpressions.info gives the answer ;)

S = S.replaceAll("\(\)", "") = the argument is a regular expression.

Because the method's first argument is a regex expression, and () are special characters in regex, so you need to escape them.

Because parentheses are special characters in regexps, so you need to escape them. To get a literal \ in a string in Java you need to escape it like so : \\.
So () => \(\) => \\(\\)

Related

Android '\' special character

I have an android application where I have to find out if my user entered the special character '\' on a string. But i'm not obtaining success by using the string.replaceAll() method, because Java recognizes \ as the end of the string, instead of the " closing tag. Does anyone have suggestions of how can I fix this?
Here is an example of how I tried to do this:
private void ReplaceSpecial(String text) {
if (text.trim().length() > 0) {
text = text.replaceAll("\", "%5C");
}
It does not work because Java doesn't allow me. Any suggestions?
Try this: You have to use escape character '\'
text = text.replaceAll("\\\\", "%5C");
Try
text = text.replaceAll("\\\\", "%5C");
replaceAll uses regex syntax where \ is special character, so you need to escape it. To do it you need to pass \\ to regex engine but to create string representing regex \\ you need to write it as "\\\\" (\ is also special character in String and requires another escaping for each \)
To avoid this regex mess you can just use replace which is working on literals
text = text.replace("\\", "%5C");
The first parameter to replaceAll is interpreted as a regular expression, so you actually need four backslashes:
text = text.replaceAll("\\\\", "%5C");
four backslashes in a string literal means two backslashes in the actual String, which in turn represents a regular expression that matches a single backslash character.
Alternatively, use replace instead of replaceAll, as recommended by Pshemo, which treats its first argument as a literal string instead of a regex.
text = text.replaceAll("\", "%5C");
Should be:
text = text.replaceAll("\\\\", "%5C");
Why?
Since the backward slash is an escape character. If you want to represent a real backslash, you should use double \ (\\)
Now the first argument of replaceAll is a regular expression. So you need to escape this too! (Which will end up with 4 backslashes).
Alternatively you can use replace which doesn't expect a regex, so you can do:
text = text.replace("\\", "%5C");
First, since "\" is the escape character in Java, you need to use two backslashes to get one backslash. Second, since the replaceAll() method takes a regular expression as a parameter, you will need to escape THAT backslash as well. Thus you need to escape it by using
text = text.replaceAll("\\\\", "%5C");
I could be late but not the least.
Add \\\\ following regex to enable \.
Sample regex:
private val specialCharacters = "-#%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_\\\\"
private val PATTERN_SPECIAL_CHARACTER = "^(?=.*[$specialCharacters]).{1,20}$"
Hope it helps.

How to replace brackets in strings

I have a list of strings that contains tokens.
Token is:
{ARG:token_name}.
I also have hash map of tokens, where key is the token and value is the value I want to substitute the token with.
When I use "replaceAll" method I get error:
java.util.regex.PatternSyntaxException: Illegal repetition
My code is something like this:
myStr.replaceAll(valueFromHashMap , "X");
and valueFromHashMap contains { and }.
I get this hashmap as a parameter.
String.replaceAll() works on regexps. {n,m} is usually repetition in regexps.
Try to use \\{ and \\} if you want to match literal brackets.
So replacing all opening brackets by X works that way:
myString.replaceAll("\\{", "X");
See here to read about regular expressions (regexps) and why { and } are special characters that have to be escaped when using regexps.
As others already said, { is a special character used in the pattern (} too).
You have to escape it to avoid any confusion.
Escaping those manually can be dangerous (you might omit one and make your pattern go completely wrong) and tedious (if you have a lot of special characters).
The best way to deal with this is to use Pattern.quote()
Related issues:
How to escape a square bracket for Pattern compilation
How to escape text for regular expression in Java
Resources:
Oracle.com - JavaSE tutorial - Regular Expressions
replaceAll() takes a regular expression as a parameter, and { is a special character in regular expressions. In order for the regex to treat it as a regular character, it must be escaped by a \, which must be escaped again by another \ in order for Java to accept it. So you must use \\{.
You can remove the curly brackets with .replaceAll() in a line with square brackets
String newString = originalString.replaceAll("[{}]", "X")
eg: newString = "ARG:token_name"
if you want to further separate newString to key and value, you can use .split()
String[] arrayString = newString.split(":")
With arrayString, you can use it for your HashMap with .put(), arrayString[0] and arrayString[1]

Regular Expression for matching parentheses

What is the regular expression for matching '(' in a string?
Following is the scenario :
I have a string
str = "abc(efg)";
I want to split the string at '(' using regular expression.For that i am using
Arrays.asList(Pattern.compile("/(").split(str))
But i am getting the following exception.
java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
Escaping '(' doesn't seems to work.
Two options:
Firstly, you can escape it using a backslash -- \(
Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]
The solution consists in a regex pattern matching open and closing parenthesis
String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis,
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
// I print first "Your", in the second round trip "String"
System.out.println(part);
}
Writing in Java 8's style, this can be solved in this way:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
I hope it is clear.
You can escape any meta-character by using a backslash, so you can match ( with the pattern
\(.
Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
Some flavors support \Q and \E, with literal text between them.
Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.
See also: Regular Expression Basic Syntax Reference
For any special characters you should use '\'.
So, for matching parentheses - /\(/
Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

Removing literal character in regex

I have the following string
\Qpipe,name=office1\E
And I am using a simplified regex library that doesn't support the \Q and \E.
I tried removing them
s.replaceAll("\\Q", "").replaceAll("\\E", "")
However, I get the error Caused by: java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1
\E
^
Any ideas?
\ is the special escape character in both Java string and regex engine. To pass a literal \ to the regex engine you need to have \\\\ in the Java string. So try:
s.replaceAll("\\\\Q", "").replaceAll("\\\\E", "")
Alternatively and a simpler way would be to use the replace method which takes string and not regex:
s.replace("\\Q", "").replace("\\E", "")
Use the Pattern.quote() function to escape special characters in regex for example
s.replaceAll(Pattern.quote("\Q"), "")
replaceAll takes a regular expression string. Instead, just use replace which takes a literal string. So myRegexString.replace("\\Q", "").replace("\\E", "").
But that still leaves you with the problem of quoting special regex characters for your simplified regex library.
String.replaceAll() takes a regular expression as parameter, so you need to escape your backslash twice:
s.replaceAll("\\\Q", "").replaceAll("\\\\E", "");
You can also use the below. I used this because i was matching and replacing a text wrapped and the Q & E would stay in the pattern. This way it doesn't.
final int flags = Pattern.LITERAL;
regex = "My regex";
pattern = Pattern.compile( regex, flags );

String replace function

I have following string
String str = "replace :) :) with some other string";
And I want to replace first occurance of :) with some other string
And I used str.replaceFirst(":)","hi");
it gives following exception
"Unmatched closing ')'"
I tried using replace function but it replaced all occurance of :).
The replaceFirst method takes a regular expression as its first parameter. Since ) is a special character in regular expressions, you must quote it. Try:
str.replaceFirst(":\\)", "hi");
The double backslashes are needed because the double-quoted string also uses backslash as a quote character.
The first argument to replaceFirst() is a regular expression, not just a character sequence. In regular expressions, the parantheses have special significance. You should escape the paranthesis like this:
str = str.replaceFirst(":\\)", "hi");
Apache Jakarta Commons are often the solution for this class of problems. In this case, I would have a look at commons-lang, espacially StringUtils.replaceOnce().

Categories