Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for extracting date from string

Tags:

regex

I have the following date string - "2013-02-20T17:24:33Z"

I want to write a regex to extract just the date part "2013-02-20". How do I do that? Any help will be appreciated.

Thanks, Murtaza

like image 874
murtaza52 Avatar asked Feb 28 '13 07:02

murtaza52


People also ask

What is the regex for date?

The regex matches on a date with the DD/MM/YYYY format and a "Date of birth:" or "Birthday:" prefix (Year min: 1900, Year max: 2020). For example: Date of birth: 12/01/1900.

What is '?' In regex?

The '?' means match zero or one space. This will match "Kaleidoscope", as well as all the misspellings that are common, the [] meaning match any of the alternatives within the square brackets.

How do you slice a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How extract all numbers from string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.


3 Answers

You could use capture group for this.

/(\d{4}-\d{2}-\d{1,2}).*/

Using $1, you can get your desired part.

like image 85
Ali Shah Ahmed Avatar answered Sep 22 '22 10:09

Ali Shah Ahmed


Well straightforward approach would be \d\d\d\d-\d\d-\d\d but you can also use quantifiers to make it look nicer \d{4}-\d{2}-\d{2}.

like image 38
Rudolfs Bundulis Avatar answered Sep 21 '22 10:09

Rudolfs Bundulis


Just search for the first T and use substring. I assume you always get a well-formatted date string.

If the date string is not guaranteed to be valid, you can use any date related library to parse and validate the input (validation includes the calendar logic, which regex fails to achieve), and reformat the output.

No sample code, since you didn't mention the language.

like image 30
nhahtdh Avatar answered Sep 22 '22 10:09

nhahtdh