将模式中的通配符替换为其他文本+相同的数字

2024-06-23 02:35:19 发布

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

我需要在这个特定的模式中找到一个大文本字符串的所有部分:

"\t\t" + number (between 1-999) + "\t\t" 

然后将每个引用替换为:

^{pr2}$

因此,最终结果是:

'TEXT\t\t24\t\tblah blah blahTEXT\t\t56\t\t'... and so on...

不同的数字介于1-999之间,因此需要某种通配符。在

有人能教我怎么做吗?谢谢!在


Tags: and字符串text文本numbersoon模式
1条回答
网友
1楼 · 发布于 2024-06-23 02:35:19

您需要使用Python的re库,尤其是re.sub函数:

import re  # re is Python's regex library
SAMPLE_TEXT = "\t\t45\t\tbsadfd\t\t839\t\tds532\t\t0\t\t"  # Test text to run the regex on

# Run the regex using re.sub (for substitute)
# re.sub takes three arguments: the regex expression,
# a function to return the substituted text,
# and the text you're running the regex on.

# The regex looks for substrings of the form:
# Two tabs ("\t\t"), followed by one to three digits 0-9 ("[0-9]{1,3}"),
# followed by two more tabs.

# The lambda function takes in a match object x,
# and returns the full text of that object (x.group(0))
# with "TEXT" prepended.
output = re.sub("\t\t[0-9]{1,3}\t\t",
                lambda x: "TEXT" + x.group(0),
                SAMPLE_TEXT)

print output  # Print the resulting string.

相关问题 更多 >