所以我认为我知道一点正则表达式,但似乎我发现了一个 case ,我的知识到了尽头. 不管怎么说,我试了以下Regex Replace function: in cases of no match, $1 returns full line instead of null种 但主要的区别是,我不仅希望用匹配替换输入,还希望在匹配之间插入一些字符.简单地说,我想将输入标准化为特定的模式. 我希望匹配和捕获输入的特定部分的正则表达式,但不是全部

^[\D]*(?P<from_day>(0?[1-9])|([12][0-9])|3[01])[\.\-\s,■]+(?P<from_month>(0?[1-9])|(1[0-2]))[\.\-\s,■]*(?P<until_day>(0?[1-9])|[12][0-9]|3[01])[\.\-\s,■]+(?P<until_month>(0?[1-9])|1[012])[\D]*$

替换字符串:

\g<from_day>.\g<from_month>-\g<until_day>.\g<until_month>

输入:

28.11 16.12
"13.01 23,09"
01.08.-31.12
"01.01,-51.12"
"01,01.-31,12."
01083112
1.02 - 4.3

当前输出:

28.11-16.12.-.
13.01-23.09.-.
01.08-31.12.-.
.-..-.
01.01-31.12.-.
.-..-.
1.02-4.3.-.

预期/所需:

28.11-16.12
13.01-23.09
01.08-31.12

01.01-31.12

1.02-4.3

https://regex101.com/r/M3arvW/1

推荐答案

您应该将您的正则表达式更改为:

^\D*(?P<from_day>[12]\d|3[01]|0?[1-9])[.\s,■-]+(?P<from_month>1[0-2]|0?[1-9])[.\s,■-]*(?P<until_day>[12]\d|3[01]|0?[1-9])[.\s,■-]+(?P<until_month>1[012]|0?[1-9]).*|.+

Updated RegEx Demo

这将解决所有问题,但不匹配时除外.如果没有匹配项,则应使用lambda函数re.sub替换为空字符串.

Python Code:

>>> import re
>>> arr = ['"01,01.-31,12."', '01083112', '1.02 - 4.3', '"01.01,-51.12"']
>>> rx = re.compile(r'^\D*(?P<from_day>[12]\d|3[01]|0?[1-9])[.\s,■-]+(?P<from_month>1[0-2]|0?[1-9])[.\s,■-]*(?P<until_day>[12]\d|3[01]|0?[1-9])[.\s,■-]+(?P<until_month>1[012]|0?[1-9]).*|.+')
>>> for i in arr: print (rx.sub(lambda m: m.group('from_day') + '.' + m.group('from_month') + '-' + m.group('until_day') + '.' + m.group('until_month') if m.group('from_day') else '', i))
...
01.01-31.12

1.02-4.3

Python相关问答推荐

获取Azure Pipelines以从pyproject.toml(而不是relevments_dev.文本)安装测试环境

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

使用polars .滤镜进行切片速度比pandas .loc慢

Pydantic 2.7.0模型接受字符串日期时间或无

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

将图像拖到另一个图像

如何让程序打印新段落上的每一行?

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

为什么默认情况下所有Python类都是可调用的?

Python虚拟环境的轻量级使用

Python中绕y轴曲线的旋转

Pandas DataFrame中行之间的差异

如何在Polars中从列表中的所有 struct 中 Select 字段?

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

使用Python从URL下载Excel文件

Plotly Dash Creating Interactive Graph下拉列表

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

基于行条件计算(pandas)

剪切间隔以添加特定日期

将一个双框爆炸到另一个双框的范围内