gpt4 book ai didi

python - 在 Python 中实现正则表达式以替换文本文件中每次出现的 "meshname = x"

转载 作者:行者123 更新时间:2023-12-04 03:35:08 25 4
gpt4 key购买 nike

我想用“”替换文本文件中的每一行,“”以“meshname =”开头,以任何字母/数字和下划线组合结尾。我在 CS 中使用了正则表达式,但我从未真正理解 Python 中的不同符号。你能帮我吗?

这是解决我的问题的正确正则表达式吗?我如何将其转换为 Python 正则表达式?

m.e.s.h.n.a.m.e.' '.=.' '.{{_}*,{0,...,9}*,{a,...,z}*,{A,...,Z}*}*

x.y = Concatenation of x and y
' ' = whitespace
{x} = set containing x
x* = x.x.x. ... .x or empty word

为了用 Python 正则表达式替换包含 meshname = ... 的文件中的每个字符串/行,脚本会是什么样子?是这样的吗?

fin = open("test.txt", 'r')
data = fin.read()
data = data.replace("^meshname = [[a-z]*[A-Z]*[0-9]*[_]*]+", "")
fin.close()
fin = open("test.txt", 'w')
fin.write(data)
fin.close()

或者这是完全错误的?我试图让它使用这种方法,但不知何故它从未匹配正确的字符串:How to input a regex in string.replace?

最佳答案

按照目前的代码逻辑,可以使用

data = re.sub(r'^meshname = .*\w$', ' ', data, flags=re.M)

re.sub 将用空格替换任何匹配的行

  • ^ - 行开始(注意 flags=re.M 参数确保多行模式开启)
  • meshname - meshname 单词
  • = - = 字符串
  • .* - 尽可能多的除换行符以外的任何零个或多个字符
  • \w - 一个字母/数字/_
  • $ - 行尾。

关于python - 在 Python 中实现正则表达式以替换文本文件中每次出现的 "meshname = x",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67061348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com