Regular expression to extract numbers from a string

后端 未结 4 584
盖世英雄少女心
盖世英雄少女心 2020-12-09 16:43

Can somebody help me construct this regular expression please...

Given the following strings...

  • \"April ( 123 widgets less 456 sprockets )\"
  • \
相关标签:
4条回答
  • 2020-12-09 17:00

    if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

    \d+
    
    0 讨论(0)
  • 2020-12-09 17:12

    we can use \b as a word boundary and then; \b\d+\b

    0 讨论(0)
  • 2020-12-09 17:14
    ^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$
    

    should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

    Explanation:

    ^     # start of string
    \s*   # optional whitespace
    (\w+) # one or more alphanumeric characters, capture the match
    \s*   # optional whitespace
    \(    # a (
    \s*   # optional whitespace
    (\d+) # a number, capture the match
    \D+   # one or more non-digits
    (\d+) # a number, capture the match
    \D+   # one or more non-digits
    \)    # a )
    \s*   # optional whitespace
    $     # end of string
    
    0 讨论(0)
  • 2020-12-09 17:16

    you could use something like:

    [^0-9]+([0-9]+)[^0-9]+([0-9]+).+

    Then get the first and second capture groups.

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