1

I have a regex to match the date formats Sep.23'15 or Sep 23'15 or Sep23'15

[a-zA-Z]{3}[. ]\d{2}'\d{2} 

I am able to match Sep.23'15 & Sep 23'15 but not Sep23'15

How to write the regex to match with space and without space ?

2
  • 2
    Use ? for [. ]. Answer: [a-zA-Z]{3}[. ]?\d{2}'\d{2} Commented Dec 18, 2015 at 6:55
  • Thanks, Working Fine. @Tushar Commented Dec 18, 2015 at 6:56

2 Answers 2

2

I suggest matching a dot (optionally) and then use * quantifier instead of the ? suggested by Tushar applied to a space:

[a-zA-Z]{3}\.?[ ]*\d{2}'\d{2} ^^^^^^^ 

This regex will also handle format like Sep. 23'15 (with a dot and a space(s) between the month and the day'year).

Regex explanation:

  • [a-zA-Z]{3} - 3 ASCII letters
  • \.? - 1 or 0 dots
  • [ ]* - zero or more regular spaces (\h, or \p{Zs}, or [[:blank:]] are recommended depending on the regex flavor if you only need to match horizontal whitespace)
  • \d{2}'\d{2} - 2 digits + ' + 2 digits.

See demo

Sign up to request clarification or add additional context in comments.

3 Comments

you use * (incorrect, as it allows Sep.......23'15 as valid) but ? (correct) in your demo... why?
@LuisColorado: I am curious why that happened myself. I took into account your remark and reconsidered my answer to better express my approach.
:) now I upvote your answer, despite it allows to use both, like Sep, 23'15 (with several blanks after the dot) better would be (\.|[ ]*) which allows either one dot or a sequence of 0 or more spaces, but not both.
0

You can use the following regex:

[A-Za-z]{3}[\.\s]?\d{1,2}\'\d{2} 

1 Comment

A dot inside a character class already matches a literal . symbol, no need escaping it. Also, OP might not want to match any whitespace (\s also matches newline symbols).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.