简体   繁体   中英

How to split string and date using regular expression

This post is closer to my problem but it did nt goes that way which i had hope:

How to split strings into text and number?

I have a string which is like this:

'Legal Leaves 2017'

I am trying to split into string and year by using this technique:

import re
match = re.match(r"([a-z]+)([0-9]+)", 'Legal Leaves 2017', re.I)
match.groups()

But i am not getting any result which means my regular expression is incorrect. Kindly help.

Obviously, 'Legal Leaves ' isn't going to match [az]+ , because it has two spaces in it, and spaces don't match the class [az] .

If you want both spaces to be part of what you match, you want to add either an explicit space or a \\s to the class: ([az\\s]+)([0-9]+) .

If you want the first space to be part of what you match, but the second space to be treated as a separator, you need to make that explicit by adding whatever separator you want (a space, any whitespace, one or more whitespace characters, etc.) in between: ([az\\s]+)\\s+([0-9]+) .

If you just want to match Leaves , then you just want the separator, but you also want to use search instead of match : ([az]+)\\s+([0-9]+) .


But meanwhile, if you don't actually understand what you're doing with regular expressions, why are you even using one here? If your format is really as static as it seems to be, you can just do this:

>>> s = 'Legal Leaves 2017'
>>> s.rpartition(' ')
('Legal Leaves', ' ', '2017')
import re
match = re.match(r"([a-z ]+) ([0-9]+)", 'Legal Leaves 2017', re.I)
print(match.groups())


output: ('Legal Leaves', '2017')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM