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

Implement regular expression in Python to replace every occurence of "meshname = x" in a text file

我想将文本文件中的每一行替换为以“meshname =”开头并以任何 letter/number 和下划线组合结尾的“ ”。我在 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 = ... 的文件中的每个 string/line,脚本应该是什么样子?是这样的吗?

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 将用 space 替换任何匹配

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