134k views
2 votes
5) Write a regular expression would zip code + 4 fields of the forms: xxxxx-xxxx where x is any number but the last 4 digits could be missing. The dash at the end of the first 5 numbers will ALWAYS be present AND the field is delineated with spaces or tabs.

User Rabbid
by
4.8k points

1 Answer

1 vote

Answer:

Following is the expression written in "Bash script" (mixture of commands):

^\d{5}(?:[-\s]\d{4})?$

Step-by-step explanation:

  • ^ = For staring string (denotation).
  • \d{5} = Matching 5 digits (first five unknown x's)
  • (?:…) = Making Group (making group of former 5 digits)
  • [-\s] = Match a hyphen or a space

(checking if a hyphen is present?)

  • \d{4} = Matching 4 digits (next four unknown x's)
  • …? = Pattern before it is optional
  • $ = Ending of the string.(denotation)

User Tomwilson
by
4.9k points