1

I have text like

input_string = " - 01 APRIL 2018 - ING000038985695286069"

i want to replace date in the string with text like DD or DATE

output_string = "- DD/DATE - ING000038985695286069"

So far, i am able to extract date from the string using

import datefinder
matches = list(datefinder.find_dates(input_string))
if len(matches) > 0:
    date = matches[0]
    print(date)

But how to get my output is my Question.

2
  • You'll have to post your code for find_dates, but I suppose you're using regular expression there. If so, just use re.sub instead of match and it'll work fine. Commented Dec 3, 2018 at 7:42
  • find_dates is a method inside datefinder library. Can you show me what you are telling Commented Dec 3, 2018 at 7:46

1 Answer 1

1

The datefinder is cool for parsing the dates out of the text, but you can omit the library and just use regular expressions (if the dates are always in the shown format).

import re

result = re.sub('\s(\d*\s\w*\s\d*)\s', ' DATE ', input_string)

Regular expression breakdown:

  • \s matches a space
  • ( start capturing the text
  • \d* match any digit as many times as possible
  • \s match exactly one space character
  • \w* match as many word characters as possible (actually also matches numbers)
  • \s again one space
  • \d* again as many digits as possible
  • ) end capturing
  • \s match one space

UPDATE
The datefinder package can be used as follows to find all dates:

dates_regex = datefinder.DateFinder().DATE_REGEX
dates_regex.sub('DATE ', input_string)

Note that this solution still uses the package, but doesn't actually do what you expect it to. It finds number sequences and replaces them too.
I would strongly suggest you build your own regex to cover exactly your needs.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey, it is not covering all my casses, if input string is 'CIwr UNdfdIadfdN ghw dfsdfdsfsT dgsggafqfe NO 9561364454 DATED 03-JULY-2018' it is not returning me any date. so my date is not going to be in same format every time. i want to extract any date from string as datefinder return
I'll pull the datefinder package and check out how we can do it with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.