How to extract numbers from a string and get an array of ints?

后端 未结 13 1027
孤城傲影
孤城傲影 2020-11-22 05:32

I have a String variable (basically an English sentence with an unspecified number of numbers) and I\'d like to extract all the numbers into an array of integers. I was wond

13条回答
  •  滥情空心
    2020-11-22 06:00

    What about to use replaceAll java.lang.String method:

        String str = "qwerty-1qwerty-2 455 f0gfg 4";      
        str = str.replaceAll("[^-?0-9]+", " "); 
        System.out.println(Arrays.asList(str.trim().split(" ")));
    

    Output:

    [-1, -2, 455, 0, 4]
    

    Description

    [^-?0-9]+
    
    • [ and ] delimites a set of characters to be single matched, i.e., only one time in any order
    • ^ Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.
    • + Between one and unlimited times, as many times as possible, giving back as needed
    • -? One of the characters “-” and “?”
    • 0-9 A character in the range between “0” and “9”

提交回复
热议问题