简体   繁体   English

使用正则表达式匹配长 integer 中的第 10 位到第 15 位数字并替换为 *

[英]Using regex to match 10th to 15th digits in a long integer and replace with *

I have a input string 12345678901234567890 and I want to use re.sub to match 10th digits to 15th digits in the above string, and replace with * so the desired output will need to be 1234567890*****67890.我有一个输入字符串 12345678901234567890,我想使用 re.sub 来匹配上述字符串中的第 10 位到第 15 位,并替换为 *,因此所需的 output 需要为 1234567890*****67890。

import re

string="12345678901234567890"
out = re.sub(".{10}\d{5}.{5}","*",string)

print(out)

Above is my current code, which is not working as expected.以上是我当前的代码,它没有按预期工作。 Does anyone has an idea on this?有人对此有想法吗? Any help would be appreciated.任何帮助,将不胜感激。

You can capture 10 digits and match the next 5 digits.您可以捕获 10 位数字并匹配接下来的 5 位数字。

^(\d{10})\d{5}

Then replace with group 1 using \1 and *****然后使用\1*****替换为组 1

Regex demo正则表达式演示

import re

string="12345678901234567890"
out = re.sub(r"^(\d{10})\d{5}",r"\1*****",string)

print(out)

Output Output

1234567890*****67890

My two cents, using PyPi's regex module with zero-width lookbehind:我的两分钱,使用 PyPi 的正则表达式模块和零宽度后视:

import regex as re

s_in = '12345678901234567890'
s_out = re.sub(r'(?<=^\d{10,14})\d(?=\d*$)', '*', s_in)

print(s_out)

Prints:印刷:

1234567890*****67890

I suppose the lookahead is not needed, but since you checking for digits anyway, why not assert that the whole string is made of digits.我想不需要前瞻,但是既然你无论如何都要检查数字,为什么不断言整个字符串是由数字组成的。

Note: This will match digits no matter the lenght of the string.注意:无论字符串的长度如何,这都会匹配数字。

If your input would always have the same width, just use a substring operation:如果您的输入总是具有相同的宽度,只需使用 substring 操作:

string = "12345678901234567890"
output = string[0:10] + "*****" + string[15:]
print(output)  # 1234567890*****67890

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

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