2

How can I extract "20151101" (as string) from "Campaign on 01.11.2015"?

I have read this one: Extracting date from a string in Python . But I am getting stuck when converting from Match object to string.

Community
  • 1
  • 1
Vũ Nam Hưng
  • 55
  • 1
  • 6

5 Answers5

9

With minor tweaks in the aforementioned post, you can get it to work.

import re
from datetime import datetime

text = "Campaign on 01.11.2015"

match = re.search(r'\d{2}.\d{2}.\d{4}', text)
date = datetime.strptime(match.group(), '%d.%m.%Y').date()
print str(date).replace("-", "")
20151101
Nickil Maveli
  • 29,155
  • 8
  • 82
  • 85
1

a slightly more robust regex: .*?\b(\d{2})\.(\d{2})\.(\d{4})\b

(nn/nn/nnnn format with word boundaries)

replace string:\3\2\1

demo

Scott Weaver
  • 7,192
  • 2
  • 31
  • 43
1

Here is one way, using re.sub():

import re

s = "Campaign on 01.11.2015"

new_s = re.sub(r"Campaign on (\d+)\.(\d+)\.(\d+)", r'\3\2\1', s)

print new_s

And another, using re.match():

import re

s = "Campaign on 01.11.2015"

match = re.match(r"Campaign on (\d+)\.(\d+)\.(\d+)", s)
new_s = match.group(3)+match.group(2)+match.group(1)

print new_s
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Lets get crazy : D

       "".join(reversed(a.split()[-1].split(".")))
Jarek Szymla
  • 79
  • 1
  • 12
0

With magic of list.

In [15]: ''.join(a.split()[-1].split('.')[::-1])
Out[15]: '20151101'
Rahul K P
  • 15,740
  • 4
  • 35
  • 52