简体   繁体   English

RegEx 美国日期格式到欧洲日期格式

[英]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匹配一个数字。 \d{1,2} matches 1 or 2 digits. \d{1,2}匹配 1 或 2 位数字。

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.所以第一组是 1-2 位,然后是破折号,第二组是 1-2 位,然后是另一个破折号,第三组是 2-4 位。 Then the replacement is just shuffling the groups around putting second group first, first group second, and third group third, separated by dashes.然后替换只是将组改组,将第二组放在第一位,第一组第二,第三组第三,用破折号隔开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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