I am having trouble with a recent Java project. I am attempting to just the String "white" from the String. No matter what method I attempt, the last "_" always remains.
String questionText = "The white house is _white_";
String correctResponse = questionText.replace(questionText.substring(0, questionText.indexOf("_")+1), "");
correctResponse.substring(0,correctResponse.length()-1);
System.out.println(correctResponse);
substring don't modify original object.
use
correctResponse = correctResponse.substring(0, correctResponse.length() - 1);
I would use a regular expression to group everything between underscores, and then String.replaceAll(String, String) to actually remove everything but the group. Like,
String correctResponse = questionText.replaceAll(".+\\s+_(.+)_", "$1"); // white
If the string you want is always between underscores (or at least after one underscore), you could just split the string and take the substring at index 1:
String correctResponse = questionText.split("_")[1];
Use lastIndexOf
String correctResponse = questionText.replace(questionText.substring(questionText.indexOf("_"), questionText.lastIndexOf("_")+1), "");
You think to complicated - why do you need replace? You can achieve the same with substring
First statement
String correctResponse = questionText.substring(questionText.indexOf("_")+1)
// ==> correctResponse = "white_"
Second statement
correctResponse = correctResponse.substring(0, correctResponse.indexOf("_"))
// ==> correctResponse = "white"
As #neuo pointed out, substring won't change the string..
You just need to change line 3.
Original Line :
correctResponse.substring(0,correctResponse.length()-1);
Correct Line :
correctResponse = correctResponse.substring(0,correctResponse.length()-1);
If you use a regular expression you don't have to check index bounaries.
String string = "Merry Christmas!".replaceAll(".$", "");
System.out.println(string);
will print out
Merry Christmas
Related
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);
I want to replace words in a string, but I am having little difficulties. Here is what I want to do. I have string:
String a = "I want to replace some words in this string";
It should work like some kind of a translator. I am doing this with String.replaceAll(), but it doesn't work completely because of this. Let's say I am translating from English to German, than this should be the output (Ich means I in German).
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
Now the output of the String a will be this:
"ich want to replace some words ich**n** **th**ich**s** **str**ich**ng**"
How to replace just the words, not the subwords in the words?
replaceAll uses regex, so you may add word boundaries or look-around mechanisms to check if there are no non-space characters surrounding word you want to replace.
String toTranslate = "I";
String translated = "Ich";
a = a.replaceAll("(?<!\\S)"+toTranslate.toLowerCase()+"(?!\\S)", translated.toLowerCase());
You can also add quotation mechanism to escape any regex metacharacters like + * ( inside word you want to replace. BTW you don't need to change your string to lower case, simply add case-insensitive flag to regex (?i).
a = a.replaceAll("(?i)(?<!\\S)"+Pattern.quote(toTranslate)+"(?!\\S)", translated.toLowerCase());
Use split(" ") for getting each word in the sentence. And then use replaceAll on each word.
String a = "I want to replace some words in this string";
String toTranslate = "I";
String translated = "Ich";
String newString[]=a.split(" ");
for (String string : newString) {
string=string.replaceAll(toTranslate, toTranslate.toLowerCase());//Adding this line ensures you dont miss any uppercase toTranslate
string=string.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
System.out.println("after translation ="+string);
}
String toTranslate = "I ";
String translated = "Ich ";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
If you add a space after the "I" it should replace it when it comes to the word "Ich" but if your word ends in a "I" then thats another problem
If you assume that I will always be capitalized in English as it should be then
a = a.replaceAll(toTranslate, translated);
will work, otherwise you need to replace both cases
a = a.replaceAll(toTranslate, translated);
a = a.replaceAll("([^a-zA-Z])("+toTranslate.toLowerCase()+")([^a-zA-Z])", "$1"+translated.toLowerCase()+"$3");
Here is a working example
Yes, the word boundaries are the solution. I just did this in the regex:
text.replaceAll("\\b" + parts1[i] + "\\b", map.element.value);
Don't be confused with the second argument it's string (from Hash table).
You can use RegEx's word bound, which is \b
String toTranslate = "\\bI\\b";
String translated = "Ich";
a = a.replaceAll(toTranslate.toLowerCase(), translated.toLowerCase());
This should ensure I is separated entirely into its own word
Edit: I misread the question and realized you want whole words. See above, as I have accounted for that
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 am using java to do a regular expression match. I am using rubular to verify the match and ideone to test my code.
I got a regex from this SO solution , and it matches the group as I want it to in rubular, but my implementation in java is not matching. When it prints 'value', it is printing the value of commaSeparatedString and not matcher.group(1) I want the captured group/output of println to be "v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso"
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
//match everything after first comma
String myRegex = ",(.*)";
Pattern pattern = Pattern.compile(myRegex);
Matcher matcher = pattern.matcher(commaSeparatedString);
String value = "";
if (matcher.matches())
value = matcher.group(1);
else
value = commaSeparatedString;
System.out.println(value);
(edit: I left out that commaSeparatedString will not always contain 2 commas. Rather, it will always contain 0 or more commas)
If you don't have to solve it with regex, you can try this:
int size = commaSeparatedString.length();
value = commaSeparatedString.substring(commaSeparatedString.indexOf(",")+1,size);
Namely, the code above returns the substring which starts from the first comma's index.
EDIT:
Sorry, I've omitted the simpler version. Thanks to one of the commentators, you can use this single line as well:
value = commaSeparatedString.substring( commaSeparatedString.indexOf(",") );
The definition of the regex is wrong. It should be:
String myRegex = "[^,]*,(.*)";
You are yet another victim of Java's misguided regex method naming.
.matches() automatically anchors the regex at the beginning and end (which is in total contradiction with the very definition of "regex matching"). The method you are looking for is .find().
However, for such a simple problem, it is better to go with #DelShekasteh's solution.
I would do this like
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
System.out.println(commaSeparatedString.substring(commaSeparatedString.indexOf(",")+1));
Here is another approach with limited split
String[] spl = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso".split(",", 2);
if (spl.length == 2)
System.out.println(spl[1]);
Byt IMHO Del's answer is best for your case.
I would use replaceFirst
String commaSeparatedString = "Vtest7,v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso";
System.out.println(commaSeparatedString.replaceFirst(".*?,", ""));
prints
v123_gpbpvl-testpv1,v223_gpbpvl-testpv1-iso
or you could use the shorter but obtuse
System.out.println(commaSeparatedString.split(",", 2)[1]);
abcd+xyz
i want to split the string and get left and right components with respect to "+"
that is i need to get abcd and xyz seperatly.
I tried the below code.
String org = "abcd+xyz";
String splits[] = org.split("+");
But i am getting null value for splits[0] and splits[1]...
Please help..
The string you send as an argument to split() is interpreted as a regex (documentation for split(String regex)). You should add an escape character before the + sign:
String splits[] = org.split("\\+");
You might also find the Summary of regular-expression constructs worth reading :)
"+" is wild character for regular expression.
So just do
String splits[] = org.split("\\+");
This will work
the expression "+" means one or many in java regular expression.
split takes Regex as a argument hence the comparion given by you fails
So use
String org = "abcd+xyz";
String splits[] = org.split(""\+");
regards!!
Try:
String splits[] = org.split("\\+");