Java-8 - replacing "?" character from the start of a Optional.of(String) - java

I'm trying to replace "?" character or delete it if my string start with ?. I tested this code and it doesn't work:
Optional<String> stringvalue = Optional.of("?test1=search&test2=ok&test3=hello");
String parameterName = "test1";
if( stringvalue.get().startsWith("?") ){
stringvalue.get().replaceFirst("\\?", "");
}
System.out.println(stringvalue.get());

You can use Optional.map as well:
stringvalue = stringvalue.map( (s) -> s.startsWith("?") ? s.replaceFirst("\\?", "") : s );

The answer is in the comment of #Aominè but how? I think you have to use :
if (stringvalue.get().startsWith("?")) {
stringvalue = Optional.of(stringvalue.get().replaceFirst("\\?", ""));
// ^^^^^^^^^^^-------note this
}
Or just :
stringvalue = Optional.of(stringvalue.get().replaceFirst("^\\?", ""));
//------------^^^^^^^^^^^---------------------------------^

Strings are immutable in Java. So stringvalue.get().replaceFirst("\\?", ""); leaves the original String value unchanged. You need to store the result of the replacement like this:
String parameterName = stringvalue.get().replaceFirst("\\?", "");
Also note that you can use ^ avoiding to test if the string startsWith ?:
String parameterName = stringvalue.get().replaceFirst("^\\?", "");

Related

"How to replace "[" from string in java?"

I want to use the String::replaceall method in Java. I have a string which includes "[" and I want to replace that with "" but it's showing an error.
String str="already data exists = [ abc,xyz,123 ]";
String replacedStr = str.replaceAll("Already Po Exits =", "");
String replacedStr1 = replacedStr.replaceAll("\\[", "");
The following replace function will replace [ in your string.
str.replaceAll("\\[", "")
or you can use replace function to achieve the same
str.replace("[", "")
For replacing Unclosed character, you need to add escape character while replacing
String replacedStr1 = replacedStr.replaceAll("\\[", "");
You can use the replace function to do this.
String replacedStr1 = replacedStr.replace("[", "");

String Manipulation in java 1.6

String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Android String format not working

I have a problem with String.format In android I want replace { 0 } with my id.
My this code not working:
String str = "abc&id={0}";
String result = String.format(str, "myId");
I think you should use replace method instead of format.
String str = "abc&id={0}";
str.replace("{0}","myId");
you have 2 ways to do that and you are mixing them :)
1.String format:
String str = "abc&id=%s";//note the format string appender %s
String result = String.format(str, "myId");
or
2.Message Format:
String str = "abc&id={0}"; // note the index here, in this case 0
String result = MessageFormat.format(str, "myId");
You have to set your integer value as a seperate variable.
String str = "abc&id";
int myId = 001;
String result = str+myId;
try this,
String result = String.format("abc&id=%s", "myId");
edit if you want more than one id,
String.format("abc&id=%s.id2=%s", "myId1", "myId2");
The syntax you're looking for is:
String str = "abc&id=%1$d";
String result = String.format(str, id);
$d because it's a decimal.
Other use case:
String.format("More %2$s for %1$s", "Steven", "coffee");
// ==> "More coffee for Steven"
which allows you to repeat an argument any number of times, at any position.

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

How to remove " " from java string

I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.
Any ideas?
cleaned = cleaned.replace(" "," ");
cleaned = cleaned.replace("\u00a0","")
This is a two step process:
strLineApp = strLineApp.replaceAll("&"+"nbsp;", " ");
strLineApp = strLineApp.replaceAll(String.valueOf((char) 160), " ");
This worked for me. Hope it helps you too!
The same way you mentioned:
String cleaned = s.replace(" "," ");
It works for me.
There's a ready solution to unescape HTML from Apache commons:
StringEscapeUtils.unescapeHtml("")
You can also escape HTML if you want:
StringEscapeUtils.escapeHtml("")
Strings are immutable so You need to do
string = string.replaceAll(" ","")
You can use JSoup library:
String date = doc.body().getElementsByClass("Datum").html().toString().replaceAll(" ","").trim();
String.replace(char, char) takes char inputs (or CharSequence inputs)
String.replaceAll(String, String) takes String inputs and matches by regular expression.
For example:
String origStr = "bat";
String newStr = str.replace('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"
The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.
For example:
String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
We can have a regular expression check and replace HTML nbsp;
input.replaceAll("[\\s\\u00A0]+$", "") + "");
It removes non breaking spaces in the input string.
My solution is the following, and only this worked for me:
String string = stringWithNbsp.replaceAll("NNBSP", "");
Strings in Java are immutable. You have to do:
String newStr = cleaned.replaceAll(" ", "");
I encountered the same problem: The inner HTML of the element I needed had "&nbsp" and my assertion failed.
Since the question has not accepted any answer,yet I would suggest the following, which worked for me
String string = stringwithNbsp.replaceAll("\n", "");
P.S : Happy testing :)

Categories