Reputation: 4709
I wanted to make a regex such that the following date can be matched and its elements passed to another function:
"21Feb14"
Now the problem is the first two digits. The user can write a date in which the 'day' field is one-digit long OR two-digit long:
"21feb14" and "1jan13"
both are valid inputs. the regex I made looks like this:
val reg = """(\\d)([a-zA-Z][a-zA-Z][a-zA-Z])(\d\d)""".r
It clearly does not take into consideration that the first digit may or may not exist. How do I handle that?
Upvotes: 1
Views: 165
Reputation: 57680
?
marks handles that. Like this,
(\d?\d)([a-zA-Z][a-zA-Z][a-zA-Z])(\d\d)
But I suggest you use following regex
(\d?\d)([a-zA-Z]{3})(\d\d)
Or with posix
(\d?\d)([\p{Alpha}]{3})(\d\d)
Upvotes: 4
Reputation: 8281
This one is far more readable and maintainable
val reg = """(\d{1,2})([a-zA-Z]{3})(\d{2})""".r
Explanations here : http://regex101.com/r/uZ9qI5
Upvotes: 2