how to extract numeric values from input string in java

后端 未结 15 1958
说谎
说谎 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 16:56

    You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer, using a try/catch approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.

    Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.

    UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that @npinti gives. That's probably the approach you should take in production code.

提交回复
热议问题