如何从字符串中删除整数部分?

时间:2018-07-25 05:46:32

标签: java selenium

我必须从列表[test, 1.1 test1, test, tsest]中删除1.1。我已经尝试了以下代码,但无法正常工作

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);

        }

3 个答案:

答案 0 :(得分:1)

这是您可以做的:

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
    }

}

答案 1 :(得分:0)

您可以在正则表达式下面使用它:

\\d*\\.?\\d+

输出:

jshell> String str = "1.1 some data"
str ==> "1.1 some data"

jshell> str = str.replaceAll("\\d*\\.?\\d+", "");
str ==> " some data"

说明:

\d - Any number 
* - 0 or more occurence
\. - Search for specific symbol .
? - zero or one occurence
+ - one or more occurence

答案 2 :(得分:0)

您可以使用正则表达式以及Matcher,Pattern组合来完成此操作,并将其全部放入某个集合中,在这种情况下为列表:

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);

    }
}

输出为:

2.1
1.0
3.0
12.0

希望这会有所帮助,

相关问题