简体   繁体   中英

RegEx American Date Format to European Date Format

I am trying to understand the following solution using Regular Expressions.

It was posted by our lecturer but he did not explain how he got to it.

This solution converts the format of an American date to a European one.

Here is the code:

import re

txt = "11-18-22"
x = re.sub(r'(\d{1,2})-(\d{1,2})-(\d{2,4})', r'\2-\1-\3', txt)
print(x)

Output:

18-11-22

Can someone explain how did that happen exactly?

\d matches a digit. \d{1,2} matches 1 or 2 digits.

The parentheses create "groups". So first group is 1-2 digits, then a dash, second group is 1-2 digits, then another dash, third group is 2-4 digits. Then the replacement is just shuffling the groups around putting second group first, first group second, and third group third, separated by dashes.

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