Python正则表达式删除包括下划线在内的所有前导数字

2024-09-30 00:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何修改现有正则表达式,使其删除所有数字或下划线的前导字符

re.sub('^(\d+|_).*', '', n, flags=re.IGNORECASE)

# test strings
0001_Smoke_B_B
0002_Smoke_B_B
0012_Smoke_B_B
MA103
MA104
00_00MA105

最终目标应该输出这些

Smoke_B_B
Smoke_B_B
Smoke_B_B
MA103
MA104
MA105

Tags: testre数字字符smokeflagsstrings前导
2条回答

如果删除.,它将使用*搜索所有数字和_

'^(\d+|_)*'

测试代码

我还从其他答案/评论中添加了'^[\d+_]+'

import re

# test strings
examples = [
    '0001_Smoke_B_B',
    '0002_Smoke_B_B',
    '0012_Smoke_B_B',
    'MA103',
    'MA104',
    '00_00MA105'
]

for text in examples:
    result = re.sub('^(\d+|_)*', '', text, flags=re.IGNORECASE)
    print(text, '->', result)

# example from other answers and comments
for text in examples:
    result = re.sub('^[\d+_]+', '', text, flags=re.IGNORECASE)
    print(text, '->', result)

用于替换的正则表达式

^[\d_]+

^这将查找字符串的开头

[\d_]带有数字或下划线的字符数组

+1次或更多次

Regex101

相关问题 更多 >

    热门问题