Extract Integer Part in String

后端 未结 8 2073
灰色年华
灰色年华 2020-11-27 06:38

What is the best way to extract the integer part of a string like

Hello123

How do you get the 123 part. You can sort of hack it using Java\

相关标签:
8条回答
  • 2020-11-27 06:55

    As explained before, try using Regular Expressions. This should help out:

    String value = "Hello123";
    String intValue = value.replaceAll("[^0-9]", ""); // returns 123
    

    And then you just convert that to an int (or Integer) from there.

    0 讨论(0)
  • 2020-11-27 06:59

    Why don't you just use a Regular Expression to match the part of the string that you want?

    [0-9]
    

    That's all you need, plus whatever surrounding chars it requires.

    Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.

    Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).

    0 讨论(0)
提交回复
热议问题