Digerkam
Digerkam

Reputation: 1921

Catching Different Number Types in Strings by Regex in PHP

I am trying to catch different number types (float, decimal, binary, octal and hex) at the beginning of strings with this regex:

/([0-9]*\.[0-9]*|0)|([1-9][0-9]*)|(0[xX][0-9a-fA-F]+)|(0[0-7]+)|(0b[01]+)|(0)/

I write it according to PHP integer page: http://php.net/manual/en/language.types.integer.php

But it is catching "a1", or only "0" part of "0xABC", I need to make it with single line of regex. What am I missing?

Upvotes: 2

Views: 70

Answers (1)

mickmackusa
mickmackusa

Reputation: 47904

I'd like to offer some important tips to resolve and refine your pattern for this task.

  • use ^ to anchor your match to the front if the input string
  • group all of the alternation branches so that every branch is bound to the "start of string" anchor.
  • several of the alternations begin with zero, so it makes sense to group these related subpatterns.
  • It is essential that you use \d*(?:\.\d+) to ensure that a dot must be followed by a digit to qualify.

Suggested Pattern: (as multi-line pattern with x flag for readability)

  /^
    (?:\d*(?:\.\d)+
    |0(?:[xX][\da-fA-F]+|[0-7]+|b[01]+)?
    |[1-9]\d*)
  /x

Upvotes: 1

Related Questions