MagePsycho
MagePsycho

Reputation: 2004

PHP Regex for validation certain number format

I need a regular expression which validates any one of the below formats:

(% without any + or - should not be validated)

I tried to use preg_match('/^[+-]?(\d+\.)?(\d+)[%]?$/', $value) but this also validates 25%.
Can anyone share regex which validates the above format?

Upvotes: 2

Views: 300

Answers (2)

anubhava
anubhava

Reputation: 784968

You may be able to do this using conditional sub-pattern in PCRE that avoids repeating whole number matching pattern again in alternation:

^([+-])?\d+(?:\.\d+)?(?(1)%)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • ([+-])?: Match + or - in optional group #1
  • \d+: Match 1+ digits
  • (?:\.\d+)?: Match dot followed by 1+ digits in an optional non-capturing group
  • (?(1)%)?: Conditional subpattern. If group #1 is present then match % as optional match.
  • $: End

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520948

I might just keep it simple here and use an alternation:

^(?:[+-]?\d+(?:\.\d+)?|[+-]\d+(?:\.\d+)?%)$

Demo

The tricky part of your requirement is that the leading sign is optional for a non percentage number, but mandatory for a percentage. The alternation makes it easy to separate out these two concerns.

Upvotes: 2

Related Questions