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

标签 python python-3.x regex replace io

我想用“”替换文本文件中的每一行,“”以“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/

相关文章:

Python镜像字符串函数

java - 匹配数字模式

Java 正则表达式模仿数字的 if-else

python - 使用 Django 从数据库中预填充 HTML 表单表

python - 如何正确卸载Anaconda?

python - 如何为 bcrypt.hashpw 设置盐?

python - Pandas : fill NaN with the closest value, 根据类别列

macos - 如何克服以下opencv问题安装?

python - split() 函数是否更改

正则表达式匹配任何不是子模式的东西