how to extract numeric values from input string in java

后端 未结 15 1967
说谎
说谎 2020-12-13 16:25

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str=\"abc d 1234567890pqr 548         


        
15条回答
  •  感情败类
    2020-12-13 17:07

    You want to discard everything except digits and spaces:

    String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();
    

    The extra calls clean up doubled and leading/trailing spaces.

    If you need an array, add a split:

    String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");
    

提交回复
热议问题