PHP - Regex for beginner

Viewed 48

My name is David from France and I need a Regex to comply with the following examples. I need to find datas between parentheses with 5 numbers, space and the name of the town, possibly followed by number of district. Here are some examples of what I need to find :

  • (05369 Toussus) OK
  • (56236 Ressons le long) OK
  • (56236 Ressons-le-long) OK
  • (44896 St-Erme-O.&R.) OK
  • (89569 amiens /1) OK
  • (89569 amiens /1/) OK
  • (56236 Ressons le long /2) OK

Here is what I don't want to comply with what I need :

  • (454683135 sdf1zg6er5e5z) KO
  • (gsdsgfdgsd 4561261) KO
  • (16 gsdvgfsvg jythjuyt) KO

I tried to use this regex but that doesn't work:

!\(([0-9]{5}.*[A-Z\-. \&\/].*[\/1-2]{2})\)!

I also tried this one but do not comply with all :

!\(([0-9]{5}.*[A-Z\-. \&\/])\)!

Can I get some help ?

Thank you in advance, David

2 Answers
/\(\d{5}\s[a-zA-Z][\w\s\-\/\.&]*\)/

\( For (

\d{5} For 5 digits

\s For A single whitespace character

[a-zA-Z] For A single letter character

[a-zA-Z] For A single letter character

[\w\s\-\/\.&]* For any number (0-infinity) of letter characters, whitespace, -, /, ., &

\) For )

Test page and PHP usage:

$pattern = '/\(\d{5}\s[a-zA-Z][\w\s\-\/\.&]*\)/m';

preg_match_all($pattern, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

If you want to capture information with capture groups, this pattern will work with Postal Code as Group 1, Name of the Town as Group 2, and District number as an optional Group 3.

/\((\d{5})\s([a-zA-Z][\w\s\-\.&]*)(?>\s\/(\d)\/*)*\)/

Edit:

By changing the character class from [a-zA-Z] to [a-zA-Z\x{00C0}-\x{017F}] you can match all accented characters as well. This changes the full expression to:

/\((\d{5})\s([a-zA-Z\x{00C0}-\x{017F}][\w\s\-\.&]*)(?>\s\/(\d)\/*)*\)/

You can change this range to whatever you want. The codes come from unicode Codes which can be found here. The range I have included goes from Latin-1 Supplement Uppercase Letters to Latin Extended-A European Latin

You might also make the pattern a bit more broader allowing any character in between the parenthesis for towns like for example Sainte-Mère-Église or École-Valentin.

Starting with french letters:

\(\d{5}\s[a-zA-ZàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒ][^()]*\)

Explanation

  • \( Match (
  • \d{5} Match 5 digits
  • \s Match a single whitespace char
  • [a-zA-ZàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒ] Match a single char in the character class
  • [^()]* Optionally match any character other than ( and )
  • \) Match )

See a regex demo.

Or starting with any letter from any language:

\(\d{5}\s\p{L}[^()]*\)

Regex demo

Related