Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Character Class Subtraction with PHP

Tags:

regex

php

HI,

I'm trying to match UK postcodes, using the pattern from http://interim.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm,

/^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z-[CIKMOV]]{2}$/

I'm using this in PHP, but it doesn't match the valid postcode OL13 0EF. This postcode does match, however, when I remove the -[CIKMOV] character class subtraction.

I get the impression that I'm doing character class subtraction wrong in PHP. I'd be most grateful if anyone could correct my error.

Thanks in advance for your help.

Ross

like image 724
Ross McFarlane Avatar asked Dec 04 '22 09:12

Ross McFarlane


1 Answers

Most of the regex flavours do not support character class subtraction. Instead you could use look-ahead assertion:

/^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9](?!.?[CIKMOV])[A-Z]{2}$/
like image 137
SilentGhost Avatar answered Jan 05 '23 17:01

SilentGhost