Unable to replace String containing special characters - java

I want to replace all special characters with whitespace but I am unable to replace x :
String search = "640×20141007151608##$%$20141008104817.jpeg";
String newSearch = search.replaceAll("[\\p{Punct}&&[^_]]", "");
System.out.println(newSearch);
output : 640×2014100715160820141008104817jpeg

I use the logic below:
String newSearch = search.replaceAll("[^A-Za-z0-9 ]","");
That is, remove anything that is not a number or a digit. Is this what you wanted ?

[^0-9a-zA-Z\.]
Try this.Repalce by ``.See demo.
http://regex101.com/r/hQ1rP0/51

Related

How to Remove string after second last occurrence of special character?

In my application I am trying to make breadcrumbs using StringBuilder
Suppose this is the string :
String1>String2>String3>String4>String5>
Now I want to remove String5> and I want string like this:
String1>String2>String3>String4>
How can I do this?
Please help!!
you can use regex \\w+>$
\\w+ mean match [a-zA-Z0-9_]
>$ match > character where $ mean at the end
Regex Demo Link
String s = "String1>String2>String3>String4>String5>";
String s2 = s.replaceAll("\\w+>$","");
System.out.println(s2);
Output :
String1>String2>String3>String4>
Note : To avoid _ use
String s2 = s.replaceAll("[a-zA-Z\\d]+>$","");
Just in case if you have data with some special characters like
String s = "String1>Stri$#$ng2>String3>Stri#$$#ng4>St$#:/|ring5>";
then above solution won't work so you can use
String s2 = s.replaceAll("[^>]+>$","");
// s2 will be = String1>Stri$#$ng2>String3>Stri#$$#ng4>
Regex Demo Link
[^>]+ : ^ inside [] works as negation mean match everything except > character
Split string by > and then apply for loop on the array. match string by position. if match then delete otherwise add to new stringBuilder.
You can use combination of lastIndexOf and substring().
Example:
String oldValue = "String1>String2>String3>String4>String5>";
int lastIndex = oldValue.lastIndexOf('>', oldValue.length() - 2);
String newValue = oldValue.substring(0, lastIndex + 1);

Regex Java when we have specific text upto a pattern

As i haven't much worked on regex, can someone help me out in getting the answer for below thing:
(1)I want to remove a text say Element
(2)It may of may not followed by delimiter say pipe(||)
I tried below thing, but it is not working in the way i want:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
System.out.println(str.replaceFirst("Element.*\\||", ""));
System.out.println(str1.replaceFirst("Element.*\\||", ""));
Required output in above cases:
String:abc||Value:abc //for the first case
String:abc //for the second case
Assuming that you can decide to give another value to the original pattern which is Element in this case, you can use Pattern.quote to escape it as below:
String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
String originalPattern = "Element";
String pattern = String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern));
System.out.println(str.replaceFirst(pattern, ""));
System.out.println(str1.replaceFirst(pattern, ""));
Your patter is then generic and its value is String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern))
Output:
String:abc||Value:abc
String:abc
You put the escape wrong. It should be:
Element(.*?\|\||.*$)
Put the escape on each pipe, and use ? for non greedy Regex so you only replace just enough string, not everything.
String text = "String:abc||Element:abc||Value:abc";
text = text.replaceAll("\\belement\\b", "");
you might need to use replace all this will replace all element from your string here i am using '\b' word boundary in java regular expression in between the words

how can I replace substring that occurs only once while excluding substring two or more times in a row?

Is there any way that I can do the following in java ?
String s = "acdaaefacaa";
String b = s.replaceLikeMethod("a", "");
and b becomes "cdaaefcaa". Basically replace any occurrence of the first string "a" with the other one "" unless "a" appears two or more times in a row.
You can use regex to achieve this. The features you want are
Negative LookBehind (?<!foo) Match pattern unless foo occurs right before.
Negative LookAhead. (?!foo) Match pattern unless foo occurs right afterwards
You basically need to use both at the same time with the same string as the string to match and pattern. E.g.
String pattern = "(?<!foo)foo(?!foo)";
Or to easily replace with a string known at runtime like "a"
String pattern = "(?<!foo)foo(?!foo)".replace("foo", "a");
Finally, to replace just do :
String b = s.replaceAll(pattern, "");
Use this regex: ((?<!a)a(?!a)). It uses negative lookahead and lookbehind. It matches every a that is not preceded and followed by another a.
Test:
String input = "acdaaefacaa";
String output = input.replaceAll("((?<!a)a(?!a))", "");
System.out.println(output);
Outputs:
cdaaefcaa

Remove all characters before special character in android

I have to remove ## before $$ from string ##$$abxcyhshbhs##xcznbx##. I am using:
string.split("\\#");
The problem is that it also removes # after $$.
Use replace() instead.
String text = "##$$abxcyhshbhs##xcznbx##";
text = text.replace("##$$", "$$");
You can use substring method like below
string.substring(2);
If you really want to use String.split() you can do what you want by limiting the number of results by doing:
String str = "##$$abxcyhshbhs##xcznbx##";
str = str.split("##", 2)[1];
I don't know your exact issue but as has already been said, replace() or substring() is probably a better option.
If you have unknown number of # symbols before $$ and they appear not just at the beginning of the string, you can use the following replaceAll with a regex:
String re = "#+\\${2}";
String str = "##$$abxcyh###$$shbhs##xcznbx##";
System.out.println(str.replaceAll(re, "\\$\\$")); // Note escaped $ !!!
// => $$abxcyh$$shbhs##xcznbx##
// or
re = "#+(\\${2})"; // using capturing and back-references
System.out.println(str.replaceAll(re, "$1"));
See IDEONE demo.
Do not forget to assign the variable a new value when using in your code:
str = str.replaceAll("#+(\\${2})", "$1")
If your purpose is to remove ## from first occurrence of ##$$ in the string, then following code snippet will be helpful:
if(yourString.startsWith("##$$")){
yourString.replaceFirst("##$$","$$");
}
OR considering there is only single $$ in your string, following would be helpful:
String requiredString="";
String[] splitArr = yourString.split("\\$");
if ( splitArr.length > 1 ) {
requiredString = "$$" + splitArr[splitArr.length-1];
}
I have written a code snippet here. You can make changes and execute on your own.
To literally remove the first two characters, use the following:
String s = "##$$abxcyhshbhs##xcznbx##";
s.substring(2, s.length());
This doesn't do any pattern matching to look for the $$.

Getting the last part of the string

I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").

Categories

Resources