This question already has answers here:
Difference between String replace() and replaceAll()
(13 answers)
Closed 4 years ago.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String searchKeyword="Legal'%_";
String specialChars[]={"_","%","'"};
for(int i=0;i<specialChars.length;i++)
searchKeyword=searchKeyword.replaceAll(specialChars[i],"\\"+specialChars[i]);
System.out.println(searchKeyword);
}
}
This snippet is trying to escape some special characters, but the issue is that searchKeyword is not getting new replaced String.
Its output should be Legal\'\%_, but I am getting the original string only as output.
Please help me in this.
replaceAll(String regex, String replacement) works with a regex :
Replaces each substring of this string that matches the given regular
expression with the given replacement.
What you need to replace a substring in an input String by a specific String is : replace(CharSequence target, CharSequence replacement).
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence.
Related
This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed last month.
Code:
public class StringBuffer_Filtering_data
{
public static void main(String[] args)
{
String [] records={
"1001.ajay.manager.account.45000.male.38",
"1002.aiswrya.clerk.account.25000.female.30",
"1003.varun.manager.sales.50000.male.35",
"1004.amit.manager.account.47000.male.40",
"1005.kareena.executive.sales.15000.female.24",
"1006.deepak.clerk.sales.23000.male.30",
"1007.sunil.accountant.sales.13000.male.29",
"1008.satvik.director.purchase.80000.male.45"
};
StringBuffer sb=new StringBuffer(255);
for(String record:records)
{
String[] fields=record.split(".");
if(fields[2].equals("manager"))
{
System.out.println(record);
}
}
}
}
Expected output:
1001,ajay,manager,account,45000,male,38
1003,varun,manager,sales,50000,male,35
1004,amit,manager,account,47000,male,40
split's argument is a regular expression (regex), not a plain old string. In the context of a regex, . is a special character while means "any character". If you want to split the string by the literal ., you'll need to escape it:
String[] fields=record.split("\\.");
// Here ----------------------^^
This question already has answers here:
Regex match entire words only
(7 answers)
Closed 5 years ago.
I need a help in regular expression, I am trying to replace "Inc" with "LLC" for many string.
I used this code in java :
String newValue = newValue.replaceAll("(?i)Inc[^\\w]","LLC");
But the result is incorrect, one char is removed after replacing :
Exp: CONSULTANTS, INC. ("ABC") ==> CONSULTANTS, LLC ("ABC") // the "." was removed.
Please note that i have used [^\w] to prevent replacing "inc" in sentences like "include".
You can use \b for word boundaries if there is no special literals in the string like ^ or ():
String s = "include inc".replaceAll("(?i)\\binc\\b", "LLC");
System.out.println(s); // (?i) is for case insensitive.
Above approach would fail if you use special characters in place of inc like ^inc. You can use Pattern.quote(s) for it to work.
If there are special characters then you can use quoted literals \Q...\E. Utility method using quoted literals:
public static String replaceExact(String str, String from, String to) {
return str.replaceAll("(?<!\\w)\\Q" + from + "\\E(?!\\w)", to);
}
Note: Pattern.quote("wor^d") will return \\Qwor^d\\E which is same as above regex.
This question already has answers here:
Regex to replace repeated characters
(2 answers)
Closed 6 years ago.
I am trying to replace all the repeated characters from a String in Java, and let only one.
For example:
aaaaa ---> a
For that, I have tried using the replaceAll method:
"aaaaa".replaceAll("a*","a") //returns "aa"
I have developed a recursive method, which is probably not very efficient:
public String recursiveReplaceAll(String original,String regex, String replacement) {
if (original.equals(original.replaceAll(regex, replacement))) return original;
return recursiveReplaceAll(original.replaceAll(regex, replacement),regex,replacement);
}
This method works, I was just wondering if there was anything using RegEx for example, which does the work with better performance.
Your replaceAll approach was nearly right - it's just that * matches 0 occurrences. You want + to mean "one or more".
"aaaaa".replaceAll("a+","a") // Returns "a"
You can do it without recursion. The regular expression "(.)\\1+" will capture every character followed by themselves at least once, and it replaces them with the captured character. Thus, this removes any repeated characters.
public static void main(String[] args) {
String str = "aaaabbbaaa";
String result = str.replaceAll("(.)\\1+", "$1");
System.out.println(result); // prints "aba".
}
With this, it works for all characters.
This question already has answers here:
How to split a string on | (pipe) in Java [duplicate]
(3 answers)
Closed 7 years ago.
I'm wondering why I cannot split a text that contain the | as a separator in String. The splitting works fine when I use commas or the like..
Here is an SSCE
package tests;
public class Tests {
public static void main(String[] args) {
String text1="one|two|three|four|five";
String text2="one,two,three,four,five";
String [] splittedText1 = text1.split("|");
String [] splittedText2 = text2.split(",");
for(String elem : splittedText1) System.out.println("text1="+elem);
for(String elem : splittedText2) System.out.println("text2="+elem);
}
}
Any ideas why it doesn't work with "|" ??
Since split(String regex) takes a regex and | is a meta character, you need to escape it.
String[] splittedText1 = splittedText1.split("\\|");
Or you can simply use Pattern class
A compiled representation of a regular expression.
String[] splittedText1 = splittedText1.split(Pattern.quote("|"));
Because the split pattern is actually a regex. You need to escape |, since it has a special meaning in the context of a regular expression (it marks an alternative):
String [] splittedText1 = text1.split("\\|");
This question already has answers here:
Why can't I split a string with the dollar sign?
(6 answers)
Closed 7 years ago.
I have a IPv6 string
String str = "demo1 26:11:d0a2:f020:0:0:0:a3:2123 demo2";
String searchString = "26:11:d0a2:f020:0:0:0:a3:2123";
When i use str.split(searchString) code returns
["demo1 ", " demo2"]
Which is fine but when i use:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "[26:11:d0a2:f020:0:0:0:a3]:2123";
and do str.split(searchString) it reutrns
[demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2]
Which is wrong i guess , can some one tell why I am getting this sort of output?
Since split function takes a regex as parameter, you need to escape those brackets otherwise this [26:11:d0a2:f020:0:0:0:a3] would match a single character only.
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
str.split(searchString);
It is happening because split(String str) take regex pattern string as argument. And that string will be used as regex pattern to match all the delimiter with this pattern.
In your regex pattern you are providing character sets in [].
To make it work your way you will have to use this regex pattern string :
\[26:11:d0a2:f020:0:0:0:a3\]:2123
i.e. in java :
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
I hope you are familiar with the string regexs. In java, the regex [abc] means match with a OR b OR c I encourage you to escape your square brackets try:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
You have to use an escape sequence for some special characters. Use \\[ ... \\] in the searchString variable.