Regular expression for extracting a number

后端 未结 4 1624
不思量自难忘°
不思量自难忘° 2020-12-22 08:45

I would like to be able to extract a number from within a string formatted as follows:

\"<[1085674730]> hello foo1, how are you doing?\"

I\'m a novice wit

相关标签:
4条回答
  • 2020-12-22 08:47

    Combine Mathews post with lookarounds http://www.regular-expressions.info/lookaround.html. This will exclude the prefix and suffix.

    (?<=<\[)\d+(?=\]>)
    

    I didn't test this regex but it should be very close to what you need. Double check at the link provided.

    Hope this helps!

    0 讨论(0)
  • 2020-12-22 08:53

    Use:

    <\[(\d+)\]>
    

    This is tested with ECMAScript regex.

    It means:

    • \[ - literal [
    • ( - open capturing group
    • \d - digit
    • + - one or more
    • ) - close capturing group
    • \] - literal ]

    The overall functionality is to capture one or more digits surrounded by the given characters.

    0 讨论(0)
  • 2020-12-22 08:58
    $subject = "<[1085674730]> hello foo1, how are you doing?";
    preg_match('/<\[(\d+)\]>/', $subject, $matches);
    

    $matches[1] will contain the number you are looking for.

    0 讨论(0)
  • 2020-12-22 09:06

    Use:

    /<\[([[:digit:]]+)\]>/
    

    If your implementation doesn't support the handy [:digit:] syntax, then use this:

    /<\[([\d]+)\]>/
    

    And if your implementation doesn't support the handy \d syntax, then use this:

    /<\[([0-9]+)\]>/
    
    0 讨论(0)
提交回复
热议问题