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);
Related
I want to get an output first-second from the string below:
first-second-third
So basically what i want is to get the string before the last dash (-).
Can anyone give me a best solution for this?
Well, many down votes but I'll add a solution
the most efficient way to do that is using java.lang.String#lastIndexOf, which returns the index within this string of the last occurrence of the specified character, searching backwards
lastIndexOf will return -1 if dash does not exist
String str = "first-second-third";
int lastIndexOf = str.lastIndexOf('-');
System.out.println(lastIndexOf);
System.out.println(str.substring(0, lastIndexOf)); // 0 represent to cut from the beginning of the string
output:
12
first-second
String s = "first-second-third";
String newString = s.substring(0,s.lastIndexOf("-"));
Just an another way other than lastIndex method, using regex too can be done, try below code:
Pattern p = Pattern.compile("\\s*(.*)-.*");
Matcher m = p.matcher("first-second-third");
if (m.find())
System.out.println(m.group(1));
I want to parse the following and store it as a new string, with the condition that mawi is stored and everything else is removed.
<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>
One solution I suppose could be a substring starting with the first character after the first > and ending two characters before the first -. All the data is identical. The result is a String with value mawi.
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String substring = initial.substring(example.indexOf(">"));
Not sure where to go from here... Any thoughts?
Although the below code do the trick, I suggest you to use Jsoup or XML Parse if you are processing multiple strings like this
Pattern pattern = Pattern.compile("<ns0:Assignee>(.+?)</ns0:Assignee>");
Matcher matcher = pattern.matcher("<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>");
matcher.find();
String result = matcher.group(1);
String finalString = result.split(" - ")[0];
System.out.println(finalString); // mawi
If all the strings are built like your example string, you could go with this:
initial.substring(initial.indexOf('>') + 1, initial.indexOf(' '));
Note the + 1 at the start index.
When your Strings are more complicated, I would recommend either using a library for working with XML or using Regular Expressions.
So now you got substring which is equal to: >mawi - Manfred Wilson</ns0:Assignee>.
Now, you can substring your substring again to find only mawi, like this;
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String midSub = initial.substring(initial.indexOf('>'));
String finalSub = midSub.substring(1, midSub.indexOf(' ')); // 1 because we still have `>`
System.out.println(finalSub);
Or, one liner:
String finalSub = initial.substring(initial.indexOf('>')+1, initial.indexOf(' '));
show this:
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(s.indexOf("<ns0:Assignee>")+"<ns0:Assignee>".length(), s.indexOf("</ns0:Assignee>"));
public class string {
public static void main(String[] args) {
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(14, 18);
System.out.println(s);
}
}
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
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").
I have a String str which can have list of values like below. I want the first letter in the string to be uppercase and if underscore appears in the string then i need to remove it and need to make the letter after it as upper case. The rest all letter i want it to be lower case.
""
"abc"
"abc_def"
"Abc_def_Ghi12_abd"
"abc__de"
"_"
Output:
""
"Abc"
"AbcDef"
"AbcDefGhi12Abd"
"AbcDe"
""
Well, without showing us that you put any effort into this problem this is going to be kinda vague.
I see two possibilities here:
Split the string at underscores, apply the answer from this question to each part and re-combine them.
Create a StringBuilder, walk through the string and keep track of whether you are
at the start of the string
after an underscore or
somewhere else
and act appropriately on the current character before appending it to the StringBuilder instance.
replace _ with space (str.replace("_", " "))
use WordUtils.capitalizeFully(str); (from commons-lang)
replace space with nothing (str.replace(" ", ""))
You can use following regexp based code:
public static String camelize(String input) {
char[] c = input.toCharArray();
Pattern pattern = Pattern.compile(".*_([a-z]).*");
Matcher m = pattern.matcher(input);
while ( m.find() ) {
int index = m.start(1);
c[index] = String.valueOf(c[index]).toUpperCase().charAt(0);
}
return String.valueOf(c).replace("_", "");
}
Use Pattern/Matcher in the java.util.regex package:
for each string that is in your array do the following:
StringBuffer output = new StringBuffer();
Matcher match = Pattern.compile("[^|_](\w)").matcher(inStr);
while(match.find()) {
match.appendReplacement(output, matcher.match(0).ToUpper());
}
match.appendTail(output);
// Will have the properly capitalized string.
String capitalized = output.ToString();
The regular expression looks for either the start of the string or an underscore "[^|_]"
Then puts the following character into a group "(\w)"
The code then goes through each of the matches in the input string capitalizing the first satisfying group.