Reputation: 79
I have to remove 1.1 from list [test, 1.1 test1, test, tsest]
. I have tries the following code but its not working
List<String> li = new ArrayList<>();
for(WebElement el : element)
{
String str = el.getText();
if(str.contains("0-9"))
{
String intValue = str.replace("[0-9]", " ");
li.add(intValue);
}else
{
li.add(str);
}
Upvotes: 0
Views: 232
Reputation: 3894
You can use below regex for that:
\\d*\\.?\\d+
Output:
jshell> String str = "1.1 some data"
str ==> "1.1 some data"
jshell> str = str.replaceAll("\\d*\\.?\\d+", "");
str ==> " some data"
Description:
\d - Any number
* - 0 or more occurence
\. - Search for specific symbol .
? - zero or one occurence
+ - one or more occurence
Upvotes: 0
Reputation: 732
Here is what you can do:
List<String> strValues = Arrays.asList("test", "1123.12345 test1",
"test", "tsest"); // Storing all the values in the List
List<String> li = new ArrayList<>(); // Creating a new list which will store the updated values of the string
for (String str : strValues) { // Iterating through the list
if (str.matches("^[0-9].*$")) { // Checking whether the string starts with a number
String newString = str.replaceAll("[-+]?([0-9]*\\.[0-9]+)", ""); // This regular expression matches an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits
li.add(newString); // Adding new string in the list
}
else {
li.add(str); //Adding the old string if the string doesn't start with a number
}
}
for (String newValue : li) {
System.out.println(newValue); // printing the list
}
}
Upvotes: 1
Reputation: 1481
You can do it with regex, and Matcher, Pattern combination, and put it all in some collection, in this case list:
public static void main (String[]args){
List<Double> listOfNumbers = new ArrayList<>();
Pattern p = Pattern.compile("\\d*\\.?\\d+");
Matcher m = p.matcher("Here is a sample with 2.1 and others 1 3 numbers and they are less than number 12");
while (m.find()) {
listOfNumbers.add(Double.valueOf(m.group()));
}
for (double num :listOfNumbers) {
System.err.println(num);
}
}
output is:
2.1
1.0
3.0
12.0
Hope this helps,
Upvotes: 0