Replace substring (replaceAll) workaround - java

I'm trying to replace a substring that contains the char "$". I'd be glad to hear why it didnt works that way, and how it would work.
Thanks,
user_unknown
public class replaceall {
public static void main(String args[]) {
String s1= "$foo - bar - bla";
System.out.println("Original string:\n"+s1);
String s2 = s1.replaceAll("bar", "this works");
System.out.println("new String:\n"+s2);
String s3 = s2.replaceAll("$foo", "damn");
System.out.println("new String:\n"+s3);
}
}

Java's .replaceAll implicitly uses Regex to replace. That means, $foo is interpreted as a regex pattern, and $ is special in regex (meaning "end of string").
You need to escape the $ as
String s3 = s2.replaceAll("\\$foo", "damn");
if the target a variable, use Pattern.quote to escape all special characters on Java ≥1.5, and if the replacement is also a variable, use Matcher.quoteReplacement.
String s3 = s2.replaceAll(Pattern.quote("$foo"), Matcher.quoteReplacement("damn"));
On Java ≥1.5, you could use .replace instead.
String s3 = s2.replace("$foo", "damn");
Result: http://www.ideone.com/Jm2c4

If you don't need Regex functionality, don't use the regex version.
Use String.replace(str, str) instead:
String s = "$$$";
String rep = s.replace("$", "€");
System.out.println(rep);
// Output: €€€
Reference:
String.replace(CharSequence, CharSequence)
String.replaceAll(String, String)

IIRC, replaceAll take a regex : Try to escape the $, this way :
String s3 = s2.replaceAll("\\$foo", "damn");

public static String safeReplaceAll(String orig, String target, String replacement) {
replacement = replacement.replace("$", "\\$");
return orig.replaceAll(target, replacement);
}

Related

Replace value in a regex

I have the next String in java:
|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|
So I need to replace the value |50200| (second one) with other value according to some decisions,but only need to replace the second one, how can I do, since replace or replaceAll don't work in this case. I was trying with some regex and appendReplacement but it did not work,also I need it to be as quick as possible, code below:
String event = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
Pattern p = Pattern.compile("^\|(\w*)\|(\d+)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|(\d+(\.\d{1,})*)\|\w+\|\w+\|\d{14}\|$");
Matcher mat = p.matcher(event);
StringBuffer aux = new StringBuffer();
mat.appendReplacement(aux, mat.group(5));
String newString = aux.toString();
But the value of newString is 50200, so basically I want to replace it with 12345, so the String would look like this |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Thanks in advance for your help
The thing is I have to use the regex to check the format of the String before doing the replace, because there could be other String with different formats
You can use indexOf to find the second position, then substring around the value you want to replace.
For example
public static void main(String[] args) {
String s = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String find = "50200";
String replace = "12345";
int firstOccur = s.indexOf(find);
int secondOccur = s.indexOf(find, firstOccur+find.length());
StringBuilder sb = new StringBuilder(s.substring(0, secondOccur));
sb.append(replace);
sb.append(s.substring(secondOccur+find.length()));
System.out.println(sb.toString());
// |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
}
Since question has been tagged as regex and non-regex solution is possible but a bit longish here is a simple one line regex solution:
String data = "|ABC|50200|100|50200|200|PRUEBA|ABC|20150220184512|";
String srch = "|50200|";
String repl = "|12345|";
String rdata = data.replaceFirst("^(.*?(\\|50200\\|).*?)\\2", "$1|12345|");
//=> |ABC|50200|100|12345|200|PRUEBA|ABC|20150220184512|
Regex ^(.*?(\|50200\|).*?)\2 finds 2nd instance of |50200| and captures everything before 2nd instance into captured group #1. We use backreference $1 in replacement to put that captured text back.
RegEx Demo

Java check and parse out string containing character sequence

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.
So if my string say myString is
"ABCDEF (Self)"
it should return myString as
"ABCDEF"
What is the best way of doing it? Can it be done in a single step?
You may use the replace function as follows:
myString = myString.replace(" (Self)","");
Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.
You may use the replaceAll method from the String class as follows:
myString = myString.replaceAll(Pattern.quote("(Self)"), ""));
Try following:
String test="ABCDEF (Self)";
test=test.replaceAll("\\(Self\\)", "");
System.out.println(test.trim());
Output :
ABCDEF
The dig is to use Regular Expressions for more on it visit this link.
And the code won't have a problem if there is no Self in string.
Just check out the String class' public methods.
String modifyString(String str) {
if(str.contains("(Self)")) {
str = str.replace("(Self)", "");
str = str.trim();
}
return str;
}
From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed.
I would recommend to use regEx if you are comfortable with it, else:
String OrigString = "ABCDEF (Self)";
String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
System.out.println("New String : --" +newString+"--");
The Regular Expression for your case would be:
\s*\(Self\)\s*
Tested Java Code using regular expression would be:
String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
System.out.println("New String : -" +newRegExpString+"--");
Output:
New String : --ABCDEF--
New String : -ABCDEF--

Java RegExp Replace

Hello I've been trying to make some replacement with not success
public class demo {
public static void main(String[] args){
String url = "/demoapi/api/user/123";
String newurl = "/user/?user=$1";
Pattern pattern = Pattern.compile("/^\\/demoapi\\/api\\/user\\/([0-9]\\d*)$/i");
Matcher match = pattern.matcher(url);
}
}
I want to replace $1 with 123 , how do I do this ?!
Thank you !
I want to replace $1 with 123 , how do I do this ?!
Simply use replace method but never forget to escape $
"/user/?user=$1".replace(/(\$1)/,"123");
I think you are looking for something like this:
String url = "/demoapi/api/user/123";
String newurl = "/user/?user=$1";
Pattern pattern = Pattern.compile(".*/user/(\\d*)");
Matcher match = pattern.matcher(url);
if(match.matches()){
newurl = newurl.replace("$1", match.group(1));
}
System.out.println(newurl);
Hope this helps.
You don't need to enter the whole text ^\\/demoapi\\/api\\/user\\ in the pattern. Just a ^.*\\/ will match upto the last / symbol. So Your java code would be,
String url = "/demoapi/api/user/123";
String newurl = "/user/?user=$1";
String m1 = url.replaceAll("(?i)^.*\\/([0-9]+)$", "$1");
String m2 = newurl.replaceAll("\\$1", m1);
System.out.println(m2);
Output:
/user/?user=123
Explanation:
(?i) Turn on the case insensitive mode.
^.*\\/ Matches upto the last / symbol.
([0-9]+)$ Captures the last digits.
IDEONE
OR
String url = "/demoapi/api/user/123";
String m1 = url.replaceAll(".*/(\\d*)$", "/user/?user=$1");
You need to put / before (\\d*), so that it would capture the numbers from starting ie, 123. Otherwise it would print the last number ie, 3.
You can use any of the following method :-
public class Test {
public static void main(String[] args) {
public static void main(String[] args) {
String url = "/demoapi/api/user/123";
String newurl = "/user/?user=$1";
String s1 = newurl.replaceAll("\\$1", Matcher.quoteReplacement("123"));
System.out.println("s1 : " + s1);
// OR
String s2 = newurl.replaceAll(Pattern.quote("$1"),Matcher.quoteReplacement("123"));
System.out.println("s2 : " + s2);
// OR
String s3 = newurl.replaceAll("\\$1", "123");
System.out.println("s3 : " + s3);
// OR
String s4 = newurl.replace("$1", "123");
System.out.println("s4 : " + s4);
}
}
Explanation of Methods Used :
Pattern.quote(String s) : Returns a literal pattern String for the
specified String. This method produces a String that can be used to
create a Pattern that would match the string s as if it were a
literal pattern. Metacharacters or escape sequences in the input
sequence will be given no special meaning.
Matcher.quoteReplacement(String s) : Returns a literal replacement
String for the specified String. This method produces a String that
will work as a literal replacement s in the appendReplacement method
of the Matcher class. The String produced will match the sequence of
characters in s treated as a literal sequence. Slashes ('\') and
dollar signs ('$') will be given no special meaning.
String.replaceAll(String regex, String replacement) : Replaces each
substring of this string that matches the given regular expression
with the given replacement.
An invocation of this method of the form str.replaceAll(regex, repl)
yields exactly the same result as the expression
Pattern.compile(regex).matcher(str).replaceAll(repl)
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.
String.replace(CharSequence target, CharSequence replacement) :
Replaces each substring of this string that matches the literal
target sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
Compact Search: .*?(\d+)$
This is all you need:
String replaced = yourString.replaceAll(".*?(\\d+)$", "/user/?user=$1");
In the regex demo, see the substitutions at the bottom.
Explanation
(\d+) matches one or more digits (this is capture Group 1)
The $ anchor asserts that we are at the end of the string
We replace with /user/?user= and Group 1, $1

How to replace \ with . in java String

I want to replace \ with . in String java.
Example src\main\java\com\myapp\AppJobExecutionListener
Here I want to get like src.main.java.com.myapp.AppJobExecutionListener
I tried str.replaceAll("\\","[.]") and str.replaceAll("\\","[.]") but it is not working.
I am still getting original string src\main\java\com\myapp\AppJobExecutionListener
String is immutable in Java, so whatever methods you invoke on the String object are not reflected on it unless you reassign it.
String s = "ABC";
s.replaceAll("B","D");
System.out.println(s); //still prints "ABC"
s = s.replaceAll("B","D");
System.out.println(s); //prints "ADC"
Currently you're using replaceAll, which takes regular expression patterns. That makes life much more complicated than it needs to be. Unless you're trying to use regular expressions, just use String.replace instead.
In fact, as you're only replacing one character with another, you can just use character literals:
String replaced = original.replace('\\', '.');
The \ is doubled as it's the escape character in Java character literals - but as the above doesn't use regular expressions, the period has no special meaning.
Assign it back to string str variable, .String#replaceAll doesn't changes the string itself, it returns a new String.
str = str.replaceAll("\\\\",".")
Can you try this:
String original = "Some text with \\ and rest of the text";
String replaced = original.replace("\\",".");
System.out.println(replaced);
'\' character is doubled in a string like '\\'. So '\\' character should be used to replace it with '.' character and also using replace instead of replaceAll would be enough to make it. Here is a sample;
public static void main(String[] args) {
String myString = "src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
System.out.println("Before Replaced: " + myString);
myString = myString.replace("\\", ".");
System.out.println("After Replaced: " + myString);
}
This will give you:
Before Replaced: src\main\java\com\vxl\appanalytix\AppJobExecutionListener
After Replaced: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
With String replaceAll(String regex, String replacement):
str = str.replaceAll("\\\\", ".");
With String replace(char oldChar, char newChar):
str = str.replace('\\', '.');
With String replace(CharSequence target, CharSequence replacement)
str = str.replace("\\", ".");
String replaced = original.replace('\', '.');
try this its works well
Use replace instead of replaceall
String my_str="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
String my_new_str = my_str.replace("\\", ".");
System.out.println(my_new_str);
DEMO AT IDEONE.COM
replaceAll takes a regex as the first parameter.
To replace the \ you need to double escape. You need an additional \ to escape the first . And as it is a regex input you need to escape those again. As other answers have said string is immutable so you will need to assign the result
String newStr = str.replaceAll("\\\\", ".");
The second parameter is not regex so you can just put . in there but note you need four slashes to replace one backslash if using replaceAll
i tried this:
String s="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
s = s.replace("\\", ".");
System.out.println("s: "+ s);
output: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
Just change the line to
str = str.replaceAll("\\",".");
Edit : I didnt try it, because the problem here is not whether its a correct regex,but the problem here is that he is not assigning the str to new str value. Anyways regex corrected now.

Wrong output using replaceall

Why do i get "AAAAAAAAA" instead of "1A234A567" from following Code:
String myst = "1.234.567";
String test = myst.replaceAll(".", "A");
System.out.println(test);
Any Idea?
Try this:
String test = myst.replace(".", "A");
The difference:
replaceAll() interprets the pattern as a regular expression, replace() interprets it as a string literal.
Here's the relevant source code from java.lang.String (indented and commented by me):
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex)
.matcher(this)
.replaceAll(replacement);
}
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(
target.toString(),
Pattern.LITERAL /* this is the difference */
).matcher(this)
.replaceAll(
Matcher.quoteReplacement(
/* replacement is also a literal,
not a pattern substitution */
replacement.toString()
));
}
Reference:
String.replaceAll(String,
String)
String.replace(CharSequence,
CharSequence)
Pattern.LITERAL
replaceAll function take a regular expression as parameter. And the regular expression "." means "any character". You have to escape it to specify that it is the character you want : replaceAll("\\.", "A")
You need to escape .
make it
String myst = "1.234.567";
String test = myst.replaceAll("\\.", "A");
System.out.println(test);
Because every single char of the input matches the regexp pattern (.). To replace dots, use this pattern: \. (or as a Java String: "\\.").

Categories

Resources