This question already has answers here:
Java Regex matching between curly braces
(5 answers)
Closed 3 years ago.
How I can fix it?
String replace1 = WEBSITE.replaceAll("{fromNumber}", number);
this character "{" error in replaceAll function. Thank you
As #Stephen C has already explained replaceall method's first argument is a regex.
Looks you are trying to replace {fromNumber} simple string with a given number. So instead of using replaceall use replace method which accepts a string as a first argument.
String replace1 = WEBSITE.replace("{fromNumber}", number);
I is not working because '{' is a regex meta-character and replaceAll is using it as so. If you want to replace all "{fromNumber}" from you String then you have to :
String replace1 = WEBSITE.replaceAll("\{fromNumber\}", number);
But if you just have to replace one then you can go with #lahiruk's answer and use
String replace1 = WEBSITE.replace("{fromNumber}", number);
Something to add here , you can use replace any number of times if you know how many times your String will contain the String to be replaced.
For more info
Syntax of regexp.
String.repaceAll()
Related
This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed 6 years ago.
I have a String called filename:
filename = "z_cams_c_ecmf_20170217000000_prod_fc_pl_015_aermr04.nc";
When I try to split the filename to get the variable name aermr04.nc, I tried the following:
String varibleName = filename.split("_")[9].split(".")[0];
The above line of code throws an IndexOutOfBoundsException.
Why?
I can get it tow work by using:
String varibleName = filename.split("_")[9].split("\\.")[0];
However, it seems rather silly that I have to fiddle around with such trivial tasks...
Any idea why the 2nd example works? What is the reasoning behind such syntax?
The argument to .split() is treated as a regular expression. "." as a regex matches everything.
To match a period, you need to escape the "." regex as "\\."
This question already has answers here:
Replace/remove String between two character [duplicate]
(3 answers)
Closed 7 years ago.
I am interested in using the String.replaceAll function that will allow me to remove a specific sequence of a String.
Does the functionality of String.replaceAll replace the first occurrence of the String sequence given to, well replace? My assumption is yes.
Going about replacing the particular sub-string, how would I replace the characters in the provided String?
String sentence = "#red##blue##green#Hello#reset#";
The substring that I want to be removed is from the # to the other #, in this case, while running String.replace
String.replaceAll("#**PATTERN HERE SO NAME WON"T MATTER**#", "");
EDIT
Seeing replace and replaceAll makes since between the two differences, being one using regex.
My concern is removing the first occurrence of the expression given, being the original string of
String sentence = "#red##blue##green#Hello#reset#";
Would have to be ran 4 times in order to have "Hello" as the remaining member of the String.
Example:
Run 1 - replaceFirstOccurence("#regex#", "");
System.out.println(sentence); --> "#blue##green#Hello#reset#"
Run 2 - replaceFirstOccurence("#regex#", "");
System.out.println(sentence); --> "#green#Hello#reset#"
Run 3 - replaceFirstOccurence("#regex#", "");
System.out.println(sentence); --> "Hello#reset#"
Run 4 - replaceFirstOccurence("#regex#", "");
System.out.println(sentence); --> "Hello"
use standart method of String replaceAll(String regularExpression, String replacement)
for example:
"#some chars#".replaceAll("#[^#]*#", "##");
Alright to answer this question is actually extremely simple but the regex was the hard part.
Thanks to #waxtah for the regex that answered this question.
Using String.replaceFirst("#[^#]*#", "");
I was able to achieve my goal. Thanks to everyone here.
This question already has answers here:
Removing repeated characters in String
(4 answers)
Closed 8 years ago.
Lets say I have a string:
tttteeeeeeessssssttttttt
Using the power of regex, how can that string be turned into:
test
At first look it seems easy to do, but the current code (not regex) I have for it is not behaving well and im pretty sure regex is the way to go.
You can use:
str = str.replaceAll("([A-Za-z])\\1+", "$1");
RegEx Demo
Use string.replaceAll function.
strng.replaceAll("(.)\\1+", "$1");
The above regex captures the first character in the sequence of same characters and matches all the following one or more characters (which must be same as the one inside the capturing group) . Replacing those characters with the character inside group index 1 will give you the desired output.
Example:
System.out.println("tttteeeeeeessssssttttttt".replaceAll("(.)\\1+","$1" ));
Output:
test
(.)(?=\1)
Try this.Replace by empty string.See demo.
https://regex101.com/r/tX2bH4/41
str = str.replaceAll("(.)(?=\\1)", "");
This question already has answers here:
Replace a question mark (?) with (\\?)
(2 answers)
replace String with another in java
(7 answers)
Closed 9 years ago.
is it possible to replace all the questionmarks ("?") with "\?" ?
Lets say I have a String, and I want to delete some parts of that String, one part with an URL in it. Like this:
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring.replaceAll(replacestring, "");
But! As I understand it you can't use the replaceAll() method with a String that contains one single questionmark, you have to make them like this "\?" first.
So the question is; Is there some way to replace questionmarks with "\?" in a String? And no, I'm able to just change the String.
Thanks in advance, hope someone understands me! (Sorry for bad English...)
Don't use replaceAll(), use replace()!
It is a common misconception that replaceAll() replaces all occurrences and replace() just replaces one or something. This is totally incorrect.
replaceAll() is poorly named - it actually replaces a regex.
replace() replaces simple Strings, which is what you want.
Both methods replace all occurrences of the target.
Just do this:
longstring = longstring.replace(replacestring, "");
And it will all work.
Escape the \ too, using \\\\?.
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring=longstring.replaceAll(replacestring, "\\\\?");
But as other answer have mentioned, replaceAll is a bit overkill, just a replace should work.
replaceAll takes a regular expression, and ? has a special meaning in the regex world.
You should use replace in this case, since you don't need a regex.
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring = longstring.replace(replacestring, "");
Oh, and strings are immutable!! longstring = longstring.replace(..), notice the assignment.
Use String.replace() instead of String.replaceAll():
longstring = longstring.replace("?", "\\?");
String.replaceAll() uses Regular Expression, while String.replace() uses plain text.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java String.replaceAll without regex
I have a string and I need to replace some parts of it.
The replacement text contains regex wild chars though. Example:
String target = "Something * to do in ('AAA', 'BBB')";
String replacement = "Hello";
String originalText = "ABCDEFHGIJKLMN" + target + "ABCDEFHGIJKLMN";
System.out.println(originalText.replaceAll(target, replacement));
I get:
ABCDEFHGIJKLMNSomething * to do in ('AAA', 'BBB')ABCDEFHGIJKLMN
Why doesn't the replacement occur?
Because *, ( and ) are all meta-characters in regular expressions. Hence all of them need to be escaped. It looks like Java has a convenient method for this:
java.util.regex.Pattern.quote(target)
However, the better option might be, to just not use the regex-using replaceAll function but simply replace. Then you do not need to escape anything.
String.replaceAll() takes a regular expression and so it's trying to expand these metacharacters.
One approach is to escape these chars (e.g. \*).
Another would be to do the replacement yourself by using String.indexOf() and finding the start of the contained string. indexOf() doesn't take a regexp but rather a normal string.