Replace the $ symbol in String [duplicate] - java

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.

Related

Identify and escape double quote, single quote and comma in Java [duplicate]

This question already has answers here:
Java, escaping (using) quotes in a regex
(2 answers)
Closed 8 years ago.
Sorry I could not find anything that works and hence I am asking this question. I have a basic string that could have feet("), inch(') or comma(,). All I want to do is identify those and escape them before further processing. Not having any luck with Regex, as you can tell I am not good with it yet. Need help. Thanks much!
Someone hinted at it in your comments, but its not entirely correct since String#replace only takes a single character, and you want to provide more than one for the replacement.
Say you have some function foo() that returns some regular expression that isn't escaped properly, with respect to the "\"" char, or the "\'" char:
String regexp = Bar.foo();
regexp = regexp.replaceAll("(\\\"|\\\')", "\\\\$0");
Pattern yourPatternName = Pattern.compile(regexp);
A little explanation: In Java, you need to escape certain special characters, such as n to mean newline ('\n'), or t to mean tab ('t'). Since you are already escaping them, they are no longer the literal characters '\' + 'n', for example. So, you need to escape them a second time, so that way when the regular expression is compiled, Pattern#compiler will see the two characters "\n" rather than the single character, which is the newline. To escape the '\n' character, you need to, of course, place in a new '\' character. Since we are doing a java.lang.String, we need to still escape that slash one more time.
As for the comma, you don't need to escape that. You only need to escape special characters. For a list of the ones that Pattern recognizes, you can check here:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Why can't I use "." as a delimiter in split() function? [duplicate]

This question already has answers here:
String.split returning null when using a dot
(4 answers)
Closed 9 years ago.
I have to take an input file, and append a number at the end to its name to use as output file. To achieve this, I use the following code:
String delimiter = ".";
String[] splitInput = inputLocation.split(delimiter);
String outputLocation = splitInput[0];
and I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
I added the following statement to check the length of the splitInput array, and I get 0 as output.
System.out.println(splitInput.length);
Later, I used ".x" as delimiter (my file being .xls). I can use ".x" and achieve my purpose but I'm curious why won't "." work?
The split function uses regular expressions, you have to escape your "." with a "\"
When using regular expressions a "." means any character. Try this
String delimiter = "\\.x";
It should also be mentioned that \ in java is also a special character used to create other special characters. Therefore you have to escape your \ with another \ hence the "\\.x"
Theres some great documentation in the Java docs about all the special characters and what they do:
Java 8 Docs
Java 7 Docs
Java 6 Docs
The . has a special meaning: Any character (may or may not match line terminators). You can escape it prepending \ or use:
[.]x
e.g.:
String delimiter = "[.]x";
See more in http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
String.split() expects a regex as input. In Java regexes, . character is a special character. Thus, your split statement is not working the way you expected. You should escape your "." as \\..
. is considered as any character in regex. Please use escape character \ (which also needs to be escaped as \\), if you want to override the special meaning of it.

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:
[.]

String.replaceAll(...) of Java not working for \\ and \

I want to convert the directory path from:
C:\Users\Host\Desktop\picture.jpg
to
C:\\Users\\Host\\Desktop\\picture.jpg
I am using replaceAll() function and other replace functions but they do not work.
How can I do this?
I have printed the statement , it gives me the one which i wanted ie
C:\Users\Host\Desktop\picture.jpg
but now when i pass this variable to open the file, i get this exception why?
java.io.FileNotFoundException: C:\Users\Host\Desktop\picture.jpg
EDIT: Changed from replaceAll to replace - you don't need a regex here, so don't use one. (It was a really poor design decision on the part of the Java API team, IMO.)
My guess (as you haven't provided enough information) is that you're doing something like:
text.replace("\\", "\\\\");
Strings are immutable in Java, so you need to use the return value, e.g.
String newText = oldText.replace("\\", "\\\\");
If that doesn't answer your question, please provide more information.
(I'd also suggest that usually you shouldn't be doing this yourself anyway - if this is to include the information in something like a JSON response, I'd expect the wider library to perform escaping for you.)
Note that the doubling is required as \ is an escape character for Java string (and character) literals. Note that as replace doesn't treat the inputs as regular expression patterns, there's no need to perform further doubling, unlike replaceAll.
EDIT: You're now getting a FileNotFoundException because there isn't a filename with double backslashes in - what made you think there was? If you want it as a valid filename, why are you doubling the backslashes?
You have to use :
String t2 = t1.replaceAll("\\\\", "\\\\\\\\");
or (without pattern) :
String t2 = t1.replace("\\", "\\\\");
Each "\" has to be preceeded by an other "\". But it's also true for the preceeding "\" so you have to write four backslashes each time you want one in regex.
In strings \ is bydefault used as escape character therefore in order to select "\" in a string you have to use "\" and for "\" (i.e blackslack two times) use "\\". This will solve your problem and thos will also apply to other symbols also like "
Two explanations:
1. Replace double backslashes to one (not what you asked)
You have to escape the backslash by backslashes. Like this:
String newPath = oldPath.replaceAll("\\\\\\\\", "\\");
The first parameter needs to be escaped twice. Once for the Java Compiler and once because you use regular expressions. So you want to replace two backslashes by one. So, since we have to escape a backslash add one backslash. Now you have \\. This will be compiled to \. BUT!! you have to escape the backslash once again because the first parameter of the replaceAll method uses regular expressions. So to escape it, add a backslash, but that backslash needs to be escaped, so we get \\\\. These for backslashes represents one backslash in the regex. But you want to replace the double backslash to one. So use 8 backslashes.
The second parameter of the replaceAll method isn't using regular expressions, but it has to be escaped as well. So, you need to escape it once for the Java Compiler and once for the replace method: \\\\. This is compiled to two backslashes, which are being interpreted as 1 backslash in the replaceAll method.
2. Replace single backslash to a pair of backslashes (what you asked)
String newPath = oldPath.replaceAll("\\\\", "\\\\\\\\");
Same logic as above.
3. Use replace() instead of replaceAll().
String newPath = oldPath.replace("\\", "\\\\");
The difference is that the replace() method doesn't use regular expressions, so you don't have to escape every backslash twice for the first parameter.
Hopefully, I explained well...
-- Edit: Fixed error, as pointed out by xehpuk --

Replace/remove String between two character [duplicate]

This question already has answers here:
Removing a substring between two characters (java)
(3 answers)
Closed 9 years ago.
I want to remove a string that is between two characters and also the characters itself , lets say for example:
i want to replace all the occurrence of the string between "#?" and ";" and remove it with the characters.
From this
"this #?anystring; is #?anystring2jk; test"
To This
"this is test"
how could i do it in java ?
#computerish your answer executes with errors in Java. The modified version works.
myString.replaceAll("#\\?.*?;", "");
The reason being the ? should be escaped by 2 backslashes else the JVM compiler throws a runtime error illegal escape character. You escape ? characters using the backslash .However, the backslash character() is itself a special character, so you need to escape it as well with another backslash.
Use regex:
myString.replaceAll("#\?.*?;", "");
string.replaceAll(start+".*"+end, "")
is the easy starting point. You might have to deal with greediness of the regex operators, however.

Categories

Resources