Reputation: 103
I've to validate a string pattern representing 2-2 letter language codes (see FacebookLocales.xml):
$languages = 'af_ZA ak_GH am_ET ar_AR as_IN ay_BO az_AZ be_BY';
So far I could come up with this:
preg_match ( "/^([a-z]{2}_[A-Z]{2}\s)+$/", $languages );
This works fine if there's a trailing space, if the trailing space is removed then it returns 0;
Upvotes: 0
Views: 798
Reputation: 626758
You can unroll your pattern like
'/^[a-z]{2}_[A-Z]{2}(?:\s+[a-z]{2}_[A-Z]{2})*$/'
or - to shorten the pattern a bit:
'/^([a-z]{2}_[A-Z]{2})(?:\s+\g<1>)*$/'
See the regex demo
The \g<1>
recurses (repeats) the subpattern defined in the first capturing group (thus, it uses [a-z]{2}_[A-Z]{2}
rather than the captured value as opposed to \1
backreference).
Upvotes: 1