开发者

create regex for several matches

I shall test a date string to see if it is one of these three: dd-mm-yyyy OR yyyy OR dd-mm-yyyy/dd-mm-yyyy

I have combine these three, but the last one makes trouble since I cannot just match a single "/" using \Q/\E.

[0-9]{2}-[0-9]{2}-[0-9]{4}                                -> dd-mm-yyyy
[0-9]{4}                                                  -> yyyy
[0-9]{2}-[0-9]{2}-[0-9]{4}\Q/\E[0-9]{2}-[0-9]{2}-[0-9]{4} -> dd-mm-yyyy/dd-mm-yyyy

Combined they will give this expression:

([0-9]{2}-[0-9]{2}-[0-9]{4}|[0-9]{4}|[0-9]{2}-[0-9]{2}-[0-9]{4}\Q/\E[0-9]{2}-[0-9]{2}-[0-9]{4})

Question 1: How to only allow a single "/" between the dates?

Question 2: What does开发者_开发知识库 a ^ mean in the start of a regex and $ in the end? And should I have it in mine

Br. Anders

UPDATE: (based on answers and comments below) Thanks! Two right answer. I marked the last one right since there also was a much smoother way to write what I had tried to do.

Language is probably XSLT or C#. It is in the CMS Umbraco that I place a regex to validate a default texstring/input field.

It acts a bit funny. There is no difference if I add a ^ to the start, therefore my question about that.

This string works perfekt: ^(?:\d{4}|\d{2}-\d{2}-\d{4}(?:/\d{2}-\d{2}-\d{4})?)$


Since you didn't specify a language, I'll suggest a working Perl version:

/^(?:\d{4}|\d{2}-\d{2}-\d{4}(?:\/\d{2}-\d{2}-\d{4})?)$/

Pattern explained:

  • start at the first character of the string
  • look for 4 digits ( \d{4} )
  • OR
  • a sequence of two digits dash two digits dash four digits
  • optionally a slash two digits dash two digits dash four digits
  • match the end of the string to make sure there is nothing else

I quoted the literal / writing \/ as it's the most cross-language way to do it: in Perl it would be enough to choose different pattern delimiter to avoid the need of escaping.


It would help if you told us which regexp variant or programming language you are using. I'll assume perl for the moment.

  • Question 1: escape it using a backslash (\) : \/.
  • Question 2: ^ means the start of the input, $ means the end. using both means match lines which exactly match my query, with no other stuff at the start or end. Since you want to match date strings, and not strings with a date in them, you should use them in your query
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜