I am programming in Java, and I have a few Strings that look similar to this:
"Avg. Price ($/lb)"
"Average Price ($/kg)"
I want to remove the ($/lb) and ($/kg) from both Strings and be left with
"Avg. Price"
"Average Price".
My code checks whether a String str variable matches one of the strings above, and if it does, replaces the text inside including the parentheses with an empty string:
if(str.matches(".*\\(.+?\\)")){
str = str.replaceFirst("\\(.+?\\)", "");
}
When I change str.matches to str.contains("$/lb"); as a test, the wanted substring is removed which leads me to believe there is something wrong with the if statement. Any help as to what I am doing wrong? Thank you.
Update I changed the if statement to:
if(str.contains("(") && str.contains (")"))
Maybe not an elegant solution but it seems to work.
String str = "Hi ($/lb)"; System.out.println("\"" + str + "\""); if (str.matches(".* \\(.+?\\)")) { str = str.replaceFirst(" \\(.+?\\)", ""); } System.out.println("\"" + str + "\"");and got the expected"Hi ($/lb)" "Hi".find()method injava.util.regex.Matcherto find non-exhaustive matches, but you really don't need to.replaceFirst()andreplaceAll()handle all the searching as well as the replacing. If they don't find any matches, they return the original string unchanged.