This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
Closed 2 years ago.
I have a snippet
public static void main(String[] args) {
// replacement text
String replacement = "Not Set";
// text
String text = "Item A \\(XXX\\) Lock"; // text is "Item A\(XXX\)Lock"
String regex = "\\(XXX\\)"; // regex is "\(XXX\)"
// result text
String resultText = text.replaceAll(regex, replacement);
System.out.println("Result text: " + resultText);
}
resultText is "Item A \(XXX\) Lock" -> I can not replace "\(XXX\)" to "Not Set".
Please help me if you know about this problem.
The regex language has its own escape sequence on top of the Java string literal escape sequence. So to match a backslash, you need \\ in the regex and thus \\\\ in the Java string literal
In this case you could also use Pattern.quote
text.replaceAll(Pattern.quote(regex), Matcher.quoteReplacement(replacement));
The characters \, ( and ) all have a special meaning when used in a regular expression. But you don't want to use them with their special meaning, which means you have to escape them in the regular expression. That means preceding them with \, to tell the regular expression processor not to invoke the special meaning of those characters.
In other words, a regular expression containing \\ will match \, a regular expression containing
\( will match ( and so on.
To match \(XXX\), the regular expression you want will be \\\(XXX\\\) - see how there's an extra \ for each \, ( and ) that you want to match. But to specify this regular expression in a Java String literal, you need to write \\ in place of each \. That is, you need to write
"\\\\\\(XXX\\\\\\)". There are six \ characters in each little run of them.
String regex = "\\\\\\(XXX\\\\\\)";
String resultText = text.replaceAll(regex, replacement);
Related
So for my app in Android Studio I want to replace the following:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("{Player1}", "Poep");
}
An example of String card can be: {Player1} switch drinks with the person next to you.
Somehow I can't use {} for the replacing. With the { it says: "Dangling metacharacter". Screenshot: https://prnt.sc/s2bbl8
Is there a solution for this?
the first Argument of replaceAll is a String that is parsed to a regalar Expression (regEx). The braces { } are special reserved meta characters to express something within the regular expression. To match them as normal characters, you need to escape them with a leading backslash \ and because the backslash is also a special character you need to escape itself with an additional backslash:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
Both { } are reserved regex characters. Since the replaceAll() function takes in a regex parameter, you have to explicitly state that { and } are part of your actual string. You can do this by prefixing them with the escape character: \. But because the escape character is also a reserved character, you need to escape it too.
Here's the correct way to write your code:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
}
You need to escape the initial { with \. I.e;
String card = "{Player1}";
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
System.out.println("replace: " + replacedCard);
}
The method String.replaceAll expects a regular expression. The other answers already give a solution for this. However, if you don't need regular expressions, then you can also use String.replace:
String replacedCard = card.replace("{Player1}", "Poep");
Since the input value of the replaceAll method expects a regex, you need to escape the curly brackets with a backslash. The curly brackets are special characters in the context of regular expressions.
In Java a backslash in a regex is accomplished by a double backslash \\ (see https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html for reference).
So you would need to adjust the line like so:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
{} are special characters for Regular Expressions. replaceAll method takes as first parameter a Regular Expressions, so if you want also to replace the curly brackets you have to skip them with \\ , as follow:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
}
I'm trying to replace some text in a file and the string contains a file path which requires some back slashes, normally using "\" works fine and produces a single \ on the output but my current code is not outputting any backslashes
String newConfig = readOld().replaceAll(readOld(),"[HKEY_CURRENT_USER\\Software\\xxxx\\xxxx\\Config]");
The "\" starts an escape sequence,
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
So, (ludicrously perhaps)
String old = readOld();
String newConfig = old.replaceAll(old,
"[HKEY_CURRENT_USER\\\\Software\\\\xxxx\\\\xxxx\\\\Config]");
Or,
String old = readOld();
char backSlash = '\\';
String newConfig = old.replaceAll(old,
"[HKEY_CURRENT_USER" + backSlash + backSlash + "Software"
+ backSlash + backSlash + "xxxx"
+ backSlash + backSlash + "xxxx"
+ backSlash + backSlash + "Config]");
You should use replace here as it may possible your readOld() method may be having some special characters (i.e +,*,. etc.) which are reserved in regExp so better to use replace.(As replaceAll may throw Exception for invalid regular Expression)
String newConfig = readOld().replace(readOld(),"replacement");
As here it seems you are replacing whole String why not just assign String directly to newConfig
From JavaDoc for replaceAll
Backslashes (\) and dollar signs ($) in the replacement
string may cause the results to be different than if it were being
treated as a literal replacement String
So either go For \\\\ (As suggested by Elliott Frinch) in String or use replace.
This question already has answers here:
Why does String.split need pipe delimiter to be escaped?
(3 answers)
Closed 9 years ago.
Just a quick question:
String input = "sam|y|rutgers";
String[] splitInput = input.split("|");
System.out.println(Arrays.toString(splitInput));
Output:
[, s, a, m, |, y, |, r, u, t, g, e, r, s]
I would like to split at the pipe characters to get
[sam,y,rutgers]
Any idea what I'm doing wrong here?
Try with one of these
split("\\|")
split("[|]")
split(Pattern.quote("|"))
split("\\Q|\\E")
split method uses regex as parameter and in regex | means OR so your current expression means empty string or empty String.
If you want to make | simple literal you need to escape it. To do this you can
place \ before it in regex engine which in String will be written as "\\|".
use character class [...] to escape most of regex metacharacters like split("[|]")
or surround your special characters with \\Q and \\E which will make every character (regardless if it is special or not) simple literal. This solution is used in Pattern.quote("regex").
You may try this:
String[] str= input.split("\\|");
"|" is a special character(OR) so you need to escape that using a slash \\. As answered here An unescaped | is parsed as a regex meaning "empty string or empty string,"
\Q & \E are regex quotes.
String[] splitInput = input.split("\\Q|\\E");
You can do it by StringTokenizer
StringTokenizer st2 = new StringTokenizer(input , "|");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
default delimeter is " " space.
StringTokenizer st2 = new StringTokenizer(input );//it will split you String by `" "` space
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Split string with | separator in java
I'm little confused as when i do the following:
String example1 = "Hello|World";
String[] splitRes;
splitRes = example1.split("|");
I don't get split string
Hello index 0
World index 1
But if I'll do
String example1 = "Hello:World";
String[] splitRes;
splitRes = example1.split(":");
then it works..
Why is it happening?
split uses a regex, you must escape the pipe because it is a "or" operator in regex:
example1.split("\\|");
String.split() expects regular expression as argument, | is a meta character "OR" in regular expression. You have to escape with \ (so it becomes \|). Note that in Java string, you have to write it as \\ since \ is also an escape character in Java string.
| is used in regular expression, .split also use regular expression so you need to escape it.
String str = ""Hello:World"; ";
String[] temp;
String delimiter = "\\|";
SepString= str.split(delimiter);
/* print test */
for(int i =0; i < SepString.length ; i++)
System.out.println(SepString[i]);
Split takes a regexp as an argument, | is a a regexp symbol.
You would have to escape it using \ which in a java string is two of them: \\
.split("\\|");
I want to split the following string "Good^Evening" i used split option it is not split the value. please help me.
This is what I've been trying:
String Val = "Good^Evening";
String[] valArray = Val.Split("^");
I'm assuming you did something like:
String[] parts = str.split("^");
That doesn't work because the argument to split is actually a regular expression, where ^ has a special meaning. Try this instead:
String[] parts = str.split("\\^");
The \\ is really equivalent to a single \ (the first \ is required as a Java escape sequence in string literals). It is then a special character in regular expressions which means "use the next character literally, don't interpret its special meaning".
The regex you should use is "\^" which you write as "\\^" as a Java String literal; i.e.
String[] parts = "Good^Evening".split("\\^");
The regex needs a '\' escape because the caret character ('^') is a meta-character in the regex language. The 2nd '\' escape is needed because '\' is an escape in a String literal.
try this
String str = "Good^Evening";
String newStr = str.replaceAll("[^]+", "");