Metal Sonic
Metal Sonic

Reputation: 61

PHP Regex to find if string is formatted with commas and semicolons

I need to find if a string is formatted in the following way:

text1,x%;text2,y%

So, these strings must be valid:

example, 10%; test, 22%; another, 90%

another example, 11.5%; yet other example, 91%

another, 11%; other example, 11.2%

example2, 20%

And the following must be invalid:

example3; 10%, test3, 22%; another3, 90%

example4; 20%

example5, 11%; test 5, 123%

another fail example, 11,5%; yet other example, 91%

I know some regex but this validation I don't even know how to start.

EDIT: Added more examples.

Upvotes: 1

Views: 942

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can use the following regex:

^[\w\s]+,\s*\d+(?:\.\d+)?%(?:;\s*[\p{L}\s]+,\s*\d+(?:\.\d+)?%)*$

See demo

Regex explanation:

Basically, it consists of 2 parts, the one before ; and the rest optional sequences.

  • ^ - Beginning of a string
  • [\w\s]+ - 1 or more alphanumeric or whitespace characters followed by...
  • , - a comma, then
  • \s* - optional whitespace
  • \d+(?:\.\d+)?% - a float or integer number (decimal part is optional due to ?) and a percentage sign
  • (?:;\s*[\p{L}\s]+,\s*\d+(?:\.\d+)?%)* - the 2nd part that matches 0 or more sequences of...
    • ;\s* - a semi-colon followed by optional whitespace
    • [\p{L}\s]+ - 1 or more letters (\p{L}) or whitespace
    • ,\s* - comma followed by optional whitespace
    • \d+(?:\.\d+)?% - a float or integer number (decimal part is optional) and a percentage sign
  • $ - End of string

Upvotes: 1

Related Questions