Search code examples
phpregexstartswith

Ensure that valid strings begin with specified literal characters using a regular expression


I'm trying to get a regular expression to work but I'm struggling due to my lack of experience with them. The idea is to scan for particular strings that begin with 'GB:'

For example it should detect:

  • GB:AB12ABC
  • GB:AB34 ABC

But not:

  • US:AB12ABC
  • AB12ABC

I have this regular expression that matches the strings I'm looking for (takes into account different spaces, formats etc):

/^([A-Z]{3}\s?(\d{3}|\d{2}|d{1})\s?[A-Z])|([A-Z]\s?(\d{3}|\d{2}|\d{1})\s?[A-Z]{3})|(([A-HK-PRSVWY][A-HJ-PR-Y])\s?([0][2-9]|[1-9][0-9])\s?[A-HJ-PR-Z]{3})$/

But now I want to add the GB: bit on the front. What would I alter in the expression above to do this?


Solution

  • I would add a GB: after the first ^, since that's what denotes the beginning of a line.

    /^GB:([A-Z]{3}\s?(\d{3}|\d{2}|d{1})\s?[A-Z])|([A-Z]\s?(\d{3}|\d{2}|\d{1})\s?[A-Z]{3})|(([A-HK-PRSVWY][A-HJ-PR-Y])\s?([0][2-9]|[1-9][0-9])\s?[A-HJ-PR-Z]{3})$/

    Edit: yeah, I suppose there is a : there. Right-o.