Regex to find an integer within a string

后端 未结 6 1372
眼角桃花
眼角桃花 2020-12-31 01:10

I\'d like to use regex with Java.

What I want to do is find the first integer in a string.

Example:

String = \"the 14 dogs ate 12 bones\"
         


        
6条回答
  •  情深已故
    2020-12-31 01:51

    the java spec actually gives this monster of a regex for parsing doubles. however it is considered bad practice, just trying to parse with the intended type, and catching the error, tends to be slightly more readable.

    DOUBLE_PATTERN = Pattern
            .compile("[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)"
                    + "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|"
                    + "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))"
                    + "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
    

提交回复
热议问题