etoolclub
etoolclub

Reputation: 31

Using regular expression failed to fetch expected date format

I am trying to extract date from the text details using regular expression but the regular expression I am using it's return nothing.

The PHP code I am using to extract date from the strings:

<?php 
preg_match("/(\w\w\w)\,(\w\w\w) (\d\d)\,(\d\d\d\d) at (\d\d)\:(\d\d)   ([A|P]M)/", $input_line, $output_array);

?>

Input strings sample:

kardashian, kim this is dummy text area
mercury, freddie Tue, Aug 23, 2016 at 2:21 PM
22.11.2016 08:58 AM
last_name, first_name
bjorge, philip 

Expected output:

Tue, Aug 23, 2016 at 2:21 PM

Please let me know why my regular expression is not working.

Thanks in advance for your help.

Upvotes: 1

Views: 44

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may fix this expression by adding space matching subpatterns, e.g. \s that matches any whitespace, or \h that matches horizontal whitespace only:

/\b(\p{L}{3}),\s(\p{L}{3})\s(\d\d),\s(\d{4})\sat\s(\d\d?):(\d\d)\s([AP]M)/
              ^^          ^^       ^^       ^^  ^^                   

See the regex demo

Wherever whitespace is optional, add * quantifier after it.

Also, to match Tue, Aug, you may just use the \p{L}{3} pattern (3 letters). Instead of \d\d\d\d you may write a shorter \d{4} equivalent. A \b word boundary in front is advisable, since you need to match the first 3-letter word as a whole word.

Also, [A|P] matches A, | or P, you need to remove the | from the character class.

Upvotes: 1

Related Questions