String.replaceAll(string,string) method gives unexpexted output - java

I have some amounts as input like:
Rs1 ,
INR10,954.00 ,
INR 45000 ,
INR 25000.70 ,
Rs.25000 ,
Rs.1,000 ,
Rs. 14000
these are the input formats I'm using
String getRuppee="Rs1"; // this string can not get the format and gives wrong output.
String val=getRuppee.toLowerCase()
.replaceAll(",", "")
.replaceAll("rs.", "")
.replaceAll("\"rs\"", "")
.replaceAll("rs", "")
.replaceAll("inr", "")
.replaceAll("inr ", "")
.replaceAll("mrp", "")
.replaceAll(" ", "");
This is how i get the output as per input show above, unless the first (Rs1).
Log.e("Converstion", "Converstion Balance."
+getRuppee.toLowerCase().
replaceAll("rs.", ""));
i need the output 1 but it gives me null.
Logcat Displays: "06-07 11:34:48.438: E/Converstion(8233): Converstion Balance."

Change your code as follows
String getRuppee="Rs1"; // this string can not get the format and gives wrong output.
String val=getRuppee.toLowerCase()
.replace(",", "")
.replace("rs.", "")
.replace("\"rs\"", "")
.replace("rs", "")
.replace("inr", "")
.replace("inr ", "")
.replace("mrp", "")
.replace(" ", "");

This is your problem here
.replaceAll("rs.", "")
As replaceAll is doing replacement based upon regexp, then this is replacing anything starting with rs followed by any char
Try using .replace instead which replaces all strings

Try below code:
String[] getRuppee = {"RS1", "INR10","954.00" , "INR 45000" , "INR 25000.70" , "Rs.25000" , "Rs.1,000" , "Rs. 14000"};
for (String tmp : getRuppee){
String val=tmp.toLowerCase()
.replaceAll(",", "")
.replaceAll("rs\\.", "") //check here
.replaceAll("\"rs\"", "")
.replaceAll("rs", "")
.replaceAll("inr", "")
.replaceAll("inr ", "")
.replaceAll("mrp", "")
.replaceAll(" ", "");
System.out.println(val);
}

Related

regular expression to replaceall substrings embedded in open curling brackets and followed by equal sign and digits

In the follwing String
String toBeFormatted= "[[LngLatAlt{longitude=-7.125924901999952, latitude=33.831783175000055, altitude=NaN},
LngLatAlt{longitude=-5.401396163999948, latitude=35.92213140900003, altitude=NaN}]]"
1- I need to replace all "LngLatAlt{longitude=" with open bracket "["
2- also need to replace all the intermediate ", latitude=33.831783175000055, altitude=NaN}" with ",33.831783175000055]"
That way my string result :
"[[[-7.125924901999952,33.831783175000055],[-5.401396163999948,35.92213140900003]]]"
try it the following reg exp :
String regexTarget = "(\\[\\[LngLatAlt\\{longitude=)";
toBeFormatted.replaceAll(regexTarget, "\\[\\[\\[");
String regexTarget0 = "(, altitude=NaN\\}, LngLatAlt\\{longitude=)";
toBeFormatted.replaceAll(regexTarget0, "],\\[");
String regexTarget1 = "(, latitude=)";
toBeFormatted.replaceAll(regexTarget1, " ,");
String regexTarget2 = "(, altitude=NaN\\})";
toBeFormatted.replaceAll(regexTarget2, "]");
but it seems not working.
Thank you for your help.
try something like:
String result = toBeFormatted.replaceAll("LngLatAlt\\{longitude=([^,]+), latitude=([^,]+), ([^}]+)\\}", "[$1, $2]");
System.out.println(result);

"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("[", "");

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

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("^\\?", "");

Java - Regex to split mathematical expression for operator excluding operator which comes under brackets

I need to split below string using below regex. but it splits data which comes under brackets.
Input
T(i-1).XX_1 + XY_8 + T(i-1).YY_2 * ZY_14
Expected Output
T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14
It should not split data which comes under "(" and ")";
I tried with below code but split data which comes under "(" and ")"
String[] result = expr.split("[+*/]");
any pointer to fix this.
I am new to this regex.
Input
(T(i-1).XX_1 + XY_8) + T(i-1).YY_2 * (ZY_14 + ZY_14)
Output
T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14 , ZY_14
if it is T(i-1) need to ignore.
For below expression its not working
XY_98 + XY_99 +XY_100
String lineExprVal = lineExpr.replaceAll("\\s+","");
String[] result = lineExprVal.split("[+*/-] (?!(^))");
You can split every thing outside your parentheses like this :
String str = "T(i-1).XX_1 + XY_8 + T(i-1).YY_2 * ZY_14";
String result[] = str.split("[+*/-] (?!(^))");
//---------------------------^----^^--List of your delimiters
System.out.println(Arrays.toString(result));
This will print :
[T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14]
The idea is simple you have to split with your delimiters that not inside your parenthesis.
You can check this here ideone and you can check your regex here Regex demo
EDIT
In your second case you have to use this regex :
String str = "(T(i - 1).XX_1 + XY_8)+ (i - 1).YY_2*(ZY_14 + ZY_14)";
String result[] = str.split("[+*+\\/-](?![^()]*(?:\\([^()]*\\))?\\))");
System.out.println(Arrays.toString(result));
This will give you :
[(T(i-1).XX_1+XY_8), T(i-1).YY_2, (ZY_14+ZY_14)]
^----Group1------^ ^--Groupe2-^ ^--Groupe3-^
You can find the Regex Demo, i inspirit this solution from this post here Regex to match only comma's but not inside multiple parentheses .
Hope this can help you.
Split in your second mathematical expression is really hard if it is not possible, so instead you have to use pattern, it is more helpful, so for your expression, you need this regex :
(\w+\([\w-*+\/]+\).\w+)|((?:(\w+\(.*?\))))|(\w+)
Here is a Demo regex you will understand more.
To get the result you need to loop throw your result :
public static void main(String[] args) {
String input = "(T(i-1).XX_1 + XY_8) + X + T(i-1).YY_2 * (ZY_14 + ZY_14) + T(i-1)";
Pattern pattern = Pattern.compile("(\\w+\\([\\w-*+\\/]+\\).\\w+)|((?:(\\w+\\(.*?\\))))|(\\w+)");
Matcher matcher = pattern.matcher(input);
List<String> reslt = new ArrayList<>();
while (matcher.find()) {//loop throw your matcher
if (matcher.group(1) != null) {
reslt.add(matcher.group(1));
}
//In your case you have to avoid this two groups
// if (matcher.group(2) != null) {
// reslt.add(matcher.group(2));
// }
// if (matcher.group(3) != null) {
// reslt.add(matcher.group(3));
// }
if (matcher.group(4) != null) {
reslt.add(matcher.group(4));
}
}
reslt.forEach(System.out::println);
}
This will gives you :
T(i-1).XX_1
XY_8
X
T(i-1).YY_2
ZY_14
ZY_14

Can't delete words from a string with replaceAll

if(containsAllWeather || containsAllWeather2){
String weatherLocation = value.toString();
if (weatherLocation != null){
weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
}
weatherLocation still gives exactly what the variable value includes and doesn't delete any of the words listed above.
This worked when I split weatherLocation to an array of strings, say, array of weatherLoc, and those lines of code worked for weatherLoc[1]
what am I doing wrong?
You need to assign the values returned by the method calls back to the String reference variable. Each time you do replaceAll() , it returns a new String object but your weatherLocation variable is still referencing to the original String.
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
Strings are immutable. You need to assign the value of all those replaceAll calls to a variable and that will be what you want.
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
Try this:
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");
String is immutable. So String.replaceAll returns a new instance of String. So you need to use like following
weatherLocation = weatherLocation.replaceAll("how","")
.replaceAll("what","")
.replaceAll("weather", "")
.replaceAll("like", "")
.replaceAll(" in", "")
.replaceAll(" at", "")
.replaceAll("around", "");

Categories