How does one match character OR nothing using regular expression

This has already been shared in a comment, but just to provide a complete-ish answer…

You have these tools at your disposal:

  • x matches x exactly once
  • x{a,b} matches x between a and b times
  • x{a,} matches x at least a times
  • x{,b} matches x up to (a maximum of) b times
  • x* matches x zero or more times (same as x{0,})
  • x+ matches x one or more times (same as x{1,})
  • x? matches x zero or one time (same as x{0,1})

So you want to use that last one, since it’s exactly what you’re looking for (zero or one time).

/\d{3}[^0-9a-zA-Z]?\d{2}[^0-9a-zA-Z]?\d{4}/

Leave a Comment

tech