Regex for Date Task

I have a line, for example: 06.07.2010 (tor.)

I want to extract only 06.07.2010 using a regular expression, but the following does not work correctly:

 ^([0-9]{1,2}).([0-9]{1,2}).([0-9]{4,4})$ ^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.]([1-9]|0[1-9]|1[012])[- /.][0-9]{4}$ 

Can someone tell me what's wrong here?

+4
source share
3 answers

This is $ at the end. This means that after the digits of the year there can be no characters - in other words, RE must match the entire string.

You probably want this:

 ^([0-9]{1,2}).([0-9]{1,2}).([0-9]{4,4}) 
+3
source

Maybe more is happening than what you are saying, or the incoming string may be more complex, but why not just use String.Split? This is much clearer IMO.

 string dateAndStuff = "06.07.2010 (tor)"; string[] parts = dateAndStuff.Split(' '); if(parts.Length > 0) { string date = parts[0]; if(!string.IsNullOrEmpty(date)) //use date } 
+1
source

The problem is that you indicate that the end of the line ($) should follow immediately after the year. If you remove this condition, you can get the date from the string. In addition, you catch the components separately, so you will not get the date as a single line. In addition, you need to avoid periods if you want them to correspond only to periods, otherwise they will match any character:

 ^([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4,4}) 

or simply:

 ^(\d{1,2}\.\d{1,2}\.\d{4}) 
0
source

Source: https://habr.com/ru/post/1314022/


All Articles