Regex to get first number in string with other characters

前端 未结 10 1479
萌比男神i
萌比男神i 2020-11-30 11:34

I\'m new to regular expressions, and was wondering how I could get only the first number in a string like 100 2011-10-20 14:28:55. In this case, I\'d want it to

10条回答
  •  离开以前
    2020-11-30 11:36

    NOTE: In Java, when you define the patterns as string literals, do not forget to use double backslashes to define a regex escaping backslash (\. = "\\.").

    To get the number that appears at the start or beginning of a string you may consider using

    ^[0-9]*\.?[0-9]+       # Float or integer, leading digit may be missing (e.g, .35)
    ^-?[0-9]*\.?[0-9]+     # Optional - before number (e.g. -.55, -100)
    ^[-+]?[0-9]*\.?[0-9]+  # Optional + or - before number (e.g. -3.5, +30)
    

    See this regex demo.

    If you want to also match numbers with scientific notation at the start of the string, use

    ^[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?        # Just number
    ^-?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?      # Number with an optional -
    ^[-+]?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?   # Number with an optional - or  +
    

    See this regex demo.

    To make sure there is no other digit on the right, add a \b word boundary, or a (?!\d) or (?!\.?\d) negative lookahead that will fail the match if there is any digit (or . and a digit) on the right.

提交回复
热议问题