查找以特定字符串开头并替换的方法是什么?

huangapple go评论50阅读模式
英文:

How to find string that startswith and replaces

问题

我有一个文件,需要搜索并替换字符串,困难在于字符串会根据先决条件而更改,我正在努力使代码工作。

文本文件:
这是一个测试文件TEST001。

在上述文本文件中,TEST001会作为其他功能的一部分更改最后三个整数。我们如何找到以TEST开头的字符串并替换为TEST002?

尝试了多种方法,但都失败了。非常感谢任何帮助。

import re

target_str = "这是一个测试文件TEST001学习"
res_str = re.sub('TEST\d{3}', 'TEST002', target_str)
# 替换后的字符串
print(res_str)

请注意,上述代码将在目标字符串中查找以"TEST"开头并后跟三个数字的字符串,并将其替换为"TEST002"。

英文:

I have a file where I need to search for string and replace, difficulty is the string changes as pre-requisite which I'm struggling to get the code working.

Text file:
This is a Test file TEST001.

In above text file TEST001 changes the last three integers as part of other functions. How can we find string that starts TEST and relpace with TEST002 ?

Tried multiple ways and failed badly. Any help would be greatly appreciated.

  import re

  target_str = "This is a Test file TEST001 learning"
  res_str = re.sub('^[TEST]' , 'TEST111', target_str)
  # String after replacement
  print(res_str)

答案1

得分: 1

你可以使用模式 \bTEST\d{3}\b -> 这将搜索 TEST 和 3 个数字。然后使用 re.sub 进行替换:

import re

target_str = "This is a Test file TEST001 learning"
res_str = re.sub(r'\bTEST\d{3}\b', 'TEST111', target_str)
print(res_str)

输出:

This is a Test file TEST111 learning
英文:

You can use pattern \bTEST\d{3}\b -> This will search for TEST and 3 digits. Then use re.sub to replace it:

import re

target_str = "This is a Test file TEST001 learning"
res_str = re.sub(r'\bTEST\d{3}\b' , 'TEST111', target_str)
print(res_str)

Prints:

This is a Test file TEST111 learning

huangapple
  • 本文由 发表于 2023年6月8日 02:56:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定