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: "\\.").
Related
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
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.
If String.replaceAll() doesn't find the desired replacement string, what will it return?
It will return the original string. the replaceAll replaces all matches, it does not matter if there are 0, 1 or 1000.
It will return the original, input String.
From the documentation:
public String replaceAll(String regex,
String replacement)
Replaces each substring of this string that matches the given regular
expression with the given replacement.
Test:
String input = "aaa";
String result = input.replaceAll("b", "c"); // Replace "b" letters for "c".
System.out.println(result); // Prints "aaa".
I need to remove a doubled letter from a string using regex operations in java.
Eg: PRINCEE -> PRINCE
APPLE -> APLE
Simple Solution (remove duplicate characters)
Like this:
final String str = "APPLEE";
String replaced = str.replaceAll("(.)\\1", "$1");
System.out.println(replaced);
Output:
APLE
Not just any Chracters, Letters only
As #Jim comments correctly, the above matches any double character, not just letters. Here are a few variations that just match letters:
// the basics, ASCII letters. these two are equivalent:
str.replaceAll("([A-Za-z])\\1", "$1");
str.replaceAll("(\\p{Alpha})\\1", "$1");
// Unicode Letters
str.replaceAll("(\\p{L})\\1", "$1");
// anything where Character.isLetter(ch) returns true
str.replaceAll("(\\p{javaLetter})\\1", "$1");
References:
For additional reference:
Character.isLetter(ch) (javadocs)
any method in Character of
the form Character.isXyz(char)
enables a pattern named
\p{javaXyz} (mind the
capitalization). This mechanism is
described in the Pattern
javadocs
Unicode blocks and categories can
also be matched with the \p and
\P constructs as in Perl. \p{prop}
matches if the input has the
property prop, while \P{prop} does
not match if the input has that
property. This mechanism is also
described in the Pattern
javadocs
String s = "...";
String replaced = s.replaceAll( "([A-Z])\\1", "$1" );
If you want to replace just duplicate ("AA"->"A", "AAA" -> "AA") use
public String undup(String str) {
return str.replaceAll("(\\w)\\1", "$1");
}
To replace triplicates etc use: str.replaceAll("(\\w)\\1+", "$1");
To replace only a single dupe is a long string (AAAA->AAA, AAA->AA) use: str.replaceAll("(\\w)(\\1+)", "$2");
This can be done simply by iterating over the String instead of having to resort to regexes.
StringBuilder ret=new StringBuilder(text.length());
if (text.length()==0) return "";
ret.append(text.charAt(0));
for(int i=1;i<text.length();i++){
if (text.charAt(i)!=text.charAt(i-1))
ret.append(text.charAt(i));
}
return ret.toString();
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);
}