Splitting string packagename with class - java

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("\\.");

Related

Java escaping hyphen "-" character using regex

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.

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.

java regex escape sequences

I was wondering about regex in Java and stumbled upon the use of backslashes. For instance, if I wanted to look for occurences of the words "this regex" in a text, I would do something like this:
Pattern.compile("this regex");
Nonetheless, I could also do something like this:
Pattern.compile("this\\sregex");
My question is: what is the difference between the two of them? And why do I have to type the backslash twice, I mean, why isn't \s an escape sequence in Java? Thanks in advance!
\s means any whitespace character, including tab, line feed and carriage return.
Java string literals already use \ to escape special characters. To put the character \ in a string literal, you need to write "\\". However regex patterns also use \ as their escape character, and the way to put that into a string literal is to use two, because it goes through two separate escaping processes. If you read your regex pattern from a plain text file for example, you won't need double escaping.
The reason you need two backslashes is that when you enter a regex string in Java code you are actually dealing with two parsers:
The first is the Java compiler, which is converting your string literal to a Java String.
The second is the regex parser, which is interpreting your regex, after it has been converted to a Java string and then passed to the regex parse when you call Pattern.compile.
So when you input "this\\sregex", it will be converted to the Java string "this\sregex" by the Java compiler. Then when you call Pattern.compile with the string, the backslash will be interpreted by the regex compiler as a special character.
The difference is that \s denotes a whitespace character, which can be more than just a blank space. It can be a tab, newline, line feed, to name a few.

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.

Java split on ^ (caret?) not working, is this a special character?

In Java, I am trying to split on the ^ character, but it is failing to recognize it. Escaping \^ throws code error.
Is this a special character or do I need to do something else to get it to recognize it?
String splitChr = "^";
String[] fmgStrng = aryToSplit.split(splitChr);
The ^ is a special character in Java regex - it means "match the beginning" of an input.
You will need to escape it with "\\^". The double slash is needed to escape the \, otherwise Java's compiler will think you're attempting to use a special \^ sequence in a string, similar to \n for newlines.
\^ is not a special escape sequence though, so you will get compiler errors.
In short, use "\\^".
The ^ matches the start of string. You need to escape it, but in this case you need to escape it so that the regular expression parser understands which means escaping the escape, so:
String splitChr = "\\^";
...
should get you what you want.
String.split() accepts a regex. The ^ sign is a special symbol denoting the beginning of the input sequence. You need to escape it to make it work. You were right trying to escape it with \ but it's a special character to escape things in Java strings so you need to escape the escape character with another \. It will give you:
\\^
use "\\^". Use this example as a guide:
String aryToSplit = "word1^word2";
String splitChr = "\\^";
String[] fmgStrng = aryToSplit.split(splitChr);
System.out.println(fmgStrng[0]+","+fmgStrng[1]);
It should print "word1,word2", effectively splitting the string using "\\^". The first slash is used to escape the second slash. If there were no double slash, Java would think ^ was an escape character, like the newline "\n"
None of the above answers makes no sense. Here is the right explanation.
As we all know, ^ doesn't need to be escaped in Java String.
As ^ is special charectar in RegulalExpression , it expects you to pass in \^
How do we make string \^ in java? Like this String splitstr = "\\^";

Categories