Regex to find an integer within a string

后端 未结 6 1352
眼角桃花
眼角桃花 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条回答
  •  Happy的楠姐
    2020-12-31 02:13

    It looks like the other solutions failed to handle +/- and cases like 2e3, which java.lang.Integer.parseInt(String) supports, so I'll take my go at the problem. I'm somewhat inexperienced at regex, so I may have made a few mistakes, used something that Java's regex parser doesn't support, or made it overly complicated, but the statements seemed to work in Kiki 0.5.6.

    All regular expressions are provided in both an unescaped format for reading, and an escaped format that you can use as a string literal in Java.

    To get a byte, short, int, or long from a string:

    unescaped: ([\+-]?\d+)([eE][\+-]?\d+)?
      escaped: ([\\+-]?\\d+)([eE][\\+-]?\\d+)?
    

    ...and for bonus points...

    To get a double or float from a string:

    unescaped: ([\+-]?\d(\.\d*)?|\.\d+)([eE][\+-]?(\d(\.\d*)?|\.\d+))?
      escaped: ([\\+-]?\\d(\\.\\d*)?|\\.\d+)([eE][\\+-]?(\\d(\\.\\d*)?|\\.\\d+))?
    

提交回复
热议问题