isxaker
isxaker

Reputation: 9456

How can I specify optional characters in a regular expression?

I have this regular expression.

MMM D[,] YYYY   
/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\ (\d{2})\, (\d{4})$/

How i can do this [,] is optional?

MMM D, YYYY
MMM D YYYY

Upvotes: 4

Views: 1555

Answers (3)

lostatredrock
lostatredrock

Reputation: 126

Have not tested the rest of your expression, but placing a ? after the comma will allow it 0 or 1 times. If you want to allow multiple commas you would use a * which is 0 to infinite times.

Upvotes: 5

Toto
Toto

Reputation: 91385

just do ,? that makes the comma optional.

Upvotes: 7

Spudley
Spudley

Reputation: 168685

A question mark after a character makes it optional in regex.

Upvotes: 3

Related Questions