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
Related
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!
How do I replace Double quotes a well as single quotes for instance:
I want where there is a " to be replaced by nothing at all. I have tried
String quoteid3 = quoteid2.replace('"','');
and it causes an error.
You're going to need to escape your quotes. Like so, might help:
String quoteid3 = quoteid2.replace('\"','\'');
To replace ", escape the double quotes with \".
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
//To replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
This should work:
String quoteid3 = quoteid2.replaceAll("\"", "");
There are two versions of String.replace, one that takes a pair of char values and the other that takes a pair of String values. If you want the replacement value to be empty then you need to use the string version, i.e. use double (rather than single) quotes.
String quoteid3 = quoteid2.replace("\"","");
In Java a single quoted literal is a char and so must be exactly one character - '' is not valid. Double quoted literals represent strings, so can be any number of characters from zero upwards.
For replacing " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
If you want to replace " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or alternatively if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
If you want to replace " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or alternatively if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.
So if you want to replace all Double quotes a well as single quotes by nothing at all
you can try this :
String str1="Hossam Hassan \"Greeting you\" \' \' \'";
System.out.println(str1);
String str2=str1.replaceAll("\"", "");
str2=str2.replaceAll("\'", "");
System.out.println(str2);
The result should be:
Hossam Hassan "Greeting you" ' ' '
Hossam Hassan Greeting you
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.
I want to split a string "ABC\DEF" ?
I have tried
String str = "ABC\DEF";
String[] values1 = str.split("\\");
String[] values2 = str.split("\");
But none seems to be working. Please help.
String.split() expects a regular expression. You need to escape each \ because it is in a java string (by the way you should escape on String str = "ABC\DEF"; too), and you need to escape for the regex. In the end, you will end with this line:
String[] values = str.split("\\\\");
The "\\\\" will be the \\ string, which the regex will interpret as \.
Note that String.split splits a string by regex.
One correct way1 to specify \ as delimiter, in RAW regex is:
\\
Since \ is special character in regex, you need to escape it to specify the literal \.
Putting the regex in string literal, you need to escape again, since \ is also escape character in string literal. Therefore, you end up with:
"\\\\"
So your code should be:
str.split("\\\\")
Note that this splits on every single instance of \ in the string.
Footnote
1 Other ways (in RAW regex) are:
\x5C
\0134
\u005C
In string literal (even worse than the quadruple escaping):
"\\x5C"
"\\0134"
"\\u005C"
Use it:
String str = "ABC\\DEF";
String[] values1 = str.split("\\\\");
final String HAY = "_0_";
String str = "ABC\\DEF".replace("\\", HAY);
System.out.println(Arrays.asList(str.split(HAY)));
Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?
This would be very handy in dynamically building a regular expression, without having to manually escape each individual character.
For example, consider a simple regex like \d+\.\d+ that matches numbers with a decimal point like 1.2, as well as the following code:
String digit = "d";
String point = ".";
String regex1 = "\\d+\\.\\d+";
String regex2 = Pattern.quote(digit + "+" + point + digit + "+");
Pattern numbers1 = Pattern.compile(regex1);
Pattern numbers2 = Pattern.compile(regex2);
System.out.println("Regex 1: " + regex1);
if (numbers1.matcher("1.2").matches()) {
System.out.println("\tMatch");
} else {
System.out.println("\tNo match");
}
System.out.println("Regex 2: " + regex2);
if (numbers2.matcher("1.2").matches()) {
System.out.println("\tMatch");
} else {
System.out.println("\tNo match");
}
Not surprisingly, the output produced by the above code is:
Regex 1: \d+\.\d+
Match
Regex 2: \Qd+.d+\E
No match
That is, regex1 matches 1.2 but regex2 (which is "dynamically" built) does not (instead, it matches the literal string d+.d+).
So, is there a method that would automatically escape each regex meta-character?
If there were, let's say, a static escape() method in java.util.regex.Pattern, the output of
Pattern.escape('.')
would be the string "\.", but
Pattern.escape(',')
should just produce ",", since it is not a meta-character. Similarly,
Pattern.escape('d')
could produce "\d", since 'd' is used to denote digits (although escaping may not make sense in this case, as 'd' could mean literal 'd', which wouldn't be misunderstood by the regex interpeter to be something else, as would be the case with '.').
Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?
If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.
So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:
// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";
The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.
matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
...
In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)
I wrote this pattern:
Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
And use it in this method:
String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
Then you can use it like this, for example:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}
We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*\\Q" + text + "\\E.*")
}
The only way the regex matcher knows you are looking for a digit and not the letter d is to escape the letter (\d). To type the regex escape character in java, you need to escape it (so \ becomes \\). So, there's no way around typing double backslashes for special regex chars.
The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.
There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:
regex.replaceAll("[\\W]", "\\\\$0")
Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:
> becomes \> which is equivalent to >
[ becomes \[ which is the escaped form of [
8 is still 8.
\) becomes \\\) which is the escaped forms of \ and ( concatenated.
Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].
Use this Utility function escapeQuotes() in order to escape strings in between Groups and Sets of a RegualrExpression.
List of Regex Literals to escape <([{\^-=$!|]})?*+.>
public class RegexUtils {
static String escapeChars = "\\.?![]{}()<>*+-=^$|";
public static String escapeQuotes(String str) {
if(str != null && str.length() > 0) {
return str.replaceAll("[\\W]", "\\\\$0"); // \W designates non-word characters
}
return "";
}
}
From the Pattern class the backslash character ('\') serves to introduce escaped constructs. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.
Example: String to be matched (hello) and the regex with a group is (\(hello\)). Form here you only need to escape matched string as shown below. Test Regex online
public static void main(String[] args) {
String matched = "(hello)", regexExpGrup = "(" + escapeQuotes(matched) + ")";
System.out.println("Regex : "+ regexExpGrup); // (\(hello\))
}
Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.
use
pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();
will give result as yourcontent as is