Java escaping hyphen "-" character using regex - java

I am using Java and have string which have value as shown below,
String data = "vale-cx";
data = data.replaceAll("\\-", "\\-\\");
I am replacing "-" inside of it and it is not working. Final value i am looking is "vale\-cx". Meaning, hyphen needs to be escaped.

Hyphen doesn't need to be escaped, but backslash needs to be escaped in the replacement expression, meaning you need an extra two backslashes before the hyphen (and none after):
data = data.replaceAll("-", "\\\\-");
Better yet, don't use regex at all:
data = data.replace("-", "\\-");

Try with \\\\- instead, e.g:
String data = "vale-cx";
System.out.println(data.replaceAll("\\-", "\\\\-"));

The hyphen is only special in regular expressions when used to create ranges in character classes, e.g. [A-Z]. You aren't doing that here, so you don't need any escaping at all.

Related

replace special character String with another Special character

I have a String which is path taken dynamically from my system .
i store it in a String .
C:\Users\SXR8036\Downloads\LANE-914.xls
I need to pass this path to read excel file function , but it needs the backward slashes to be replaced with forward slash.
and i want something like C:/Users/SXR8036/Downloads/LANE-914.xls
i.e all backward slash replaced with forward one
With String replace method i am only able to replace with a a-z character , but it shows error when i replace Special characters
something.replaceAll("[^a-zA-Z0-9]", "/");
I have to pass the String name to read a file.
It's better in this case to use non-regex replace() instead of regex replaceAll(). You don't need regular expressions for this replacement and it complicates things because it needs extra escapes. Backslash is a special character in Java and also in regular expressions, so in Java if you want a straight backslash you have to double it up \\ and if you want a straight backslash in a regular expression in Java you have to quadruple it \\\\.
something = something.replace("\\", "/");
Behind the scenes, replace(String, String) uses regular expression patterns (at least in Oracle JDK) so has some overhead. In your specific case, you can actually use single character replacement, which may be more efficient (not that it probably matters!):
something = something.replace('\\', '/');
If you were to use regular expressions:
something = something.replaceAll("\\\\", "/");
Or:
something = something.replaceAll(Pattern.quote("\\"), "/");
To replace backslashes with replaceAll you'll have to escape them properly in the regular expression that you are using.
In your case the correct expression would be:
final String path = "C:\\Users\\SXR8036\\Downloads\\LANE-914.xls";
final String normalizedPath = path.replaceAll("\\\\", "/");
As the backslash itself is the escape character in Java Strings it needs to be escaped twice to work as desired.
In general you can pass very complex regular expressions to String.replaceAll. See the JavaDocs of java.lang.String.replaceAll and especially java.util.regex.Pattern for more information.

Splitting string packagename with class

I don't know why this code doesn't work.
This is my code.
String value[] = pce.getPropertyName().toString().split(".");
the value of pce.getPropertyName is com.newbie.model.Names
when I debug it the size of value is 0.
Anyone encounter this problem?
. has a special meaning in regex-world (specifically, it matches any character), and recall that split() does indeed take a regular expression as an argument. You want
String value[] = pce.getPropertyName().toString().split("\\.");
i.e. escape the ..
You have to escape the dot character, since dot is a meta-character:
String value[] = pce.getPropertyName().toString().split("\\.");
If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes like \\.
Java docs for the same can be found here.
So, this is what you should do.
String value[] = pce.getPropertyName().toString().split("\\.");

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]

A simple scenario in Java where replacing a single character with a back slash requires four back slashes

Let's consider the following code snippet in Java.
package escape;
final public class Main
{
public static void main(String[] args)
{
String s = "abc/xyz";
System.out.println(s.replaceAll("/", "\\\\"));
}
}
I just want to replace "/" with "\" in the above String abc/xyz and which is done and displays abc\xyz as expected but I couldn't get why it requires back slashes four times. It looks like two back slashes are sufficient. Why such is not a case?
The reason is that String.replaceAll uses regular expressions (and actually calls Matcher.replaceAll which does document this). In regular expressions you have to escape the '\' also in string literals you have to escape the '\'. Your 4 slashes are two slashes in the java string. And thereby an escaped slash in the regular expression.
You need to escape back slash once\\ for java String and one more time\\ for regex replacement string.
From the JavaDoc:
Note that 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; see Matcher.replaceAll. Use
Matcher.quoteReplacement(java.lang.String) to suppress the special
meaning of these characters, if desired
System.out.println(s.replaceAll("/", Matcher.quoteReplacement("\\")));
I just want to replace "/" with "\"
Then you should not be using a regular expression, which is overkill, and requires backslashes to be escaped (twice). Instead do
string.replace('/', '\\');
(Still need to escape it once)
Referring to the Java documentation, if you use replaceAll, Java will treat the first parameter as a RegEx, and will assess special meaning for backslashes in the replacement string. Basically, \1 would refer to the first matching glob in the regex... In this case you need to escape the backslashes so they're "litteral" backslashes for the String, and then you need to escape these a second time so that replaceAll doesn't try to treat them with a special meaning.

Categories