How to replace \ with . in java String - java

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.

Related

String replace method issue in java

My problem is to replace only the last occurrence of a character in the string with another character. When I used the String.replace(char1, char2), it replaces all the occurrences of the character in the string.
For example, I have an address string like
String str = "Addressline1,Addressline2,City,State,Country,";.
I need to replace the occurrence of ',' at the end of the string with '.'.
My code to replace the character is
str = str.replace(str.charAt(str.lastIndexOf(",")),'.');
After replacing, the string looks like:
Addressline1.Addressline2.City.State.Country.
Is there the problem in Java SDK?. If yes, how to resolve it?
You should use String.replaceAll which use regex
str = str.replaceAll (",$", ".");
The $ mean the end of the String
The Java replace function has a method declaration of:
public String replace(char oldChar, char newChar)
According to the docs replace will:
Return a new string resulting from replacing all occurrences of oldChar in this string with newChar.
So your code:
str.charAt(str.lastIndexOf(","))
Will clearly return the character ,. replace will then replace all instances of the oldChar , with the newChar .. This explains the behavior you were seeing.
The solution that #ScaryWombat beat me to is your best option:
str = str.replaceAll(",$", ".");
Since, in regular expression terms, $ denotes the end of a String.
Hope this helps!

JAVA: Replacing words in string

I want to replace words in a string, but I am having little difficulties. Here is what I want to do. I have string:
String a = "I want to replace some words in this string";
It should work like some kind of a translator. I am doing this with String.replaceAll(), but it doesn't work completely because of this. Let's say I am translating from English to German, than this should be the output (Ich means I in German).
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
Now the output of the String a will be this:
"ich want to replace some words ich**n** **th**ich**s** **str**ich**ng**"
How to replace just the words, not the subwords in the words?
replaceAll uses regex, so you may add word boundaries or look-around mechanisms to check if there are no non-space characters surrounding word you want to replace.
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll("(?<!\\S)"+toTranslate.toLowerCase()+"(?!\\S)", translated.toLowerCase());
You can also add quotation mechanism to escape any regex metacharacters like + * ( inside word you want to replace. BTW you don't need to change your string to lower case, simply add case-insensitive flag to regex (?i).
a = a.replaceAll("(?i)(?<!\\S)"+Pattern.quote(toTranslate)+"(?!\\S)", translated.toLowerCase());
Use split(" ") for getting each word in the sentence. And then use replaceAll on each word.
String a = "I want to replace some words in this string";
String toTranslate = "I";
String translated = "Ich";
String newString[]=a.split(" ");
for (String string : newString) {
string=string.replaceAll(toTranslate, toTranslate.toLowerCase());//Adding this line ensures you dont miss any uppercase toTranslate
string=string.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
System.out.println("after translation ="+string);
}
String toTranslate = "I ";
String translated = "Ich ";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
If you add a space after the "I" it should replace it when it comes to the word "Ich" but if your word ends in a "I" then thats another problem
If you assume that I will always be capitalized in English as it should be then
a = a.replaceAll(toTranslate, translated);
will work, otherwise you need to replace both cases
a = a.replaceAll(toTranslate, translated);
a = a.replaceAll("([^a-zA-Z])("+toTranslate.toLowerCase()+")([^a-zA-Z])", "$1"+translated.toLowerCase()+"$3");
Here is a working example
Yes, the word boundaries are the solution. I just did this in the regex:
text.replaceAll("\\b" + parts1[i] + "\\b", map.element.value);
Don't be confused with the second argument it's string (from Hash table).
You can use RegEx's word bound, which is \b
String toTranslate = "\\bI\\b";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
This should ensure I is separated entirely into its own word
Edit: I misread the question and realized you want whole words. See above, as I have accounted for that

replace in java using regular expression

suppose I have a string
String = ".... helllo.... good \"morning\" .....\" "
I want to get output as
helllo good morning
How can I do that using regular expression in Java?
If you're just trying to remove the . and the ", then you can do
str = str.replaceAll("\"|\\.", "");
This regular expression replaces any " (escaped as \" because in a java string literal) or (|) . (escaped first as \. because in a regex then as \\. because a \ must be escaped in a java string literal) by nothing ("").
This
String yourString = ".... helllo.... good \"morning\" .....\" ";
System.out.println(yourString.replaceAll("[.\\\"]", ""));
outputs helllo good morning
Supposing you just want to maintain the space character and letters, you can use the following regex:
[^a-zA-Z\s]+
If you also want to include numbers:
[^a-zA-Z0-9\s]+
Just replace the matches of that regular expression by an empty string.
Edit:
If you just want to do the opposite (remove certain characters, like . and "), then you can check #dystroy answer.
public static void main(String[] args) {
String str = ".... helllo.... good \"morning\" .....\" ";
str = str.replaceAll("[^a-zA-Z]", " ").replaceAll(" +", " ");
System.out.println(str);
}
There are many ways to do this.
Here is a way to do it using simple replace methods of String class.
String s = ".... helllo.... good \"morning\" .....\" ";
s = s.replace(".","").replace("\"", "");
System.out.println(s);

replace all + with -

I am trying to replace a + character into a hyphen I have in my string.
String str = "word+word";
str.replaceAll('+ ', '-');
I tried using replace but it throwing an exception.Is there any other method to do this.
Use
str = str.replaceAll("\\+", "-");
A few errors in your code :
replaceAll takes strings, not chars
the + char must be escaped as the first argument is a regular expression (and \ itself must be escaped in java string literals)
you must take the return of the function : as String is immutable the function doesn't change it but returns another string
Just use replace:
str = str.replace('+', '-');
This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str variable because String in Java are immutable. In this case method replace doesn't change current String (str) but create new one with replaced + to '-'.
`replaceAll´ is for regular expressions and strings are immutable. Use:
str = str.replace("+", "-");
instead...
The replaceAll function takes a regular expression as its first argument. It so happens that + is a special character in regular expression language. Try replacing + with \\+. This will escape the plus sign, thus making the code to treat it like a normal character.
Also, the replaceAll method yields a string, so that will not work. Try doing:
String str = "word+word";
str = str.replaceAll("\\+ ", "-");
Use "" as opposed to '' in replaceAll.
String java.lang.String.replaceAll(String regex, String replacement)
If you are not sure about the escape sequence you need to use,
You could simply do this.
str = str.replaceAll(Pattern.quote("+"), "-");
This will automatically escape the regex predefined tokens to match in a literal way

Replace substring (replaceAll) workaround

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);
}

Categories

Resources