Comments in regular expression (?#...)

Q

Is there any way to enter a comment into regular expressions?

How to write a regular expression with comments to match date strings in yyyy-mm-dd format like: 2013-01-26

✍: FYIcenter.com

A

Yes. Comments can be entered in regular expressions using (?#...) format. For example:

"(?:[^"\]++(?#no-backtracking)|\.)*+(?#no-backtracking)"

The regular expression with comments to validate data strings:

(?#year)\d{4}-(?#month)\d{2}-(?#day)\d{2}

(?#year)   - comment
\d{4}      - 4 digits for year
(?#month)   - comment
\d{2}      - 2 digits for month
(?#day)   - comment
\d{2}      - 2 digits for day

Click the button to test this regular expression here online:

2013-01-26, 2177👍, 0💬