Regex to find an integer within a string

后端 未结 6 1370
眼角桃花
眼角桃花 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 02:10

    In addition to what PiPeep said, if you are trying to match integers within an expression, so that 1 + 2 - 3 will only match 1, 2, and 3, rather than 1, + 2 and - 3, you actually need to use a lookbehind statement, and the part you want will actually be returned by Matcher.group(2) rather than just Matcher.group().

    unescaped: ([0-9])?((?(1)(?:[\+-]?\d+)|)(?:[eE][\+-]?\d+)?)
      escaped: ([0-9])?((?(1)(?:[\\+-]?\\d+)|)(?:[eE][\\+-]?\\d+)?)
    

    Also, for things like someNumber - 3, where someNumber is a variable name or something like that, you can use

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

    Although of course that wont work if you are parsing a string like The net change to blahblah was +4

提交回复
热议问题