[英]Implement regular expression in Python to replace every occurence of "meshname = x" in a text file
I want to replace every line in a textfile with " " which starts with "meshname = " and ends with any letter/number and underscore combination.我想用“”替换文本文件中的每一行,它以“meshname =”开头并以任何字母/数字和下划线组合结尾。 I used regex's in CS but I never really understood the different notations in Python.我在 CS 中使用了正则表达式,但我从来没有真正理解 Python 中的不同表示法。 Can you help me with that?你能帮我解决这个问题吗?
Is this the right regex for my problem and how would i transform that into a Python regex?这是解决我的问题的正确正则表达式吗?我如何将其转换为 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
What would the script look like in order to replace every string/line in a file containing meshname =... with the Python regex?为了用 Python 正则表达式替换包含 meshname =... 的文件中的每个字符串/行,脚本会是什么样子? Something like this?像这样的东西?
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()
or is this completely wrong?或者这是完全错误的? I've tried to get it working with this approach, but somehow it never matched the right string: How to input a regex in string.replace?我试图让它使用这种方法,但不知何故它从未匹配正确的字符串: 如何在 string.replace 中输入正则表达式?
Following the current code logic, you can use按照当前的代码逻辑,您可以使用
data = re.sub(r'^meshname = .*\w$', ' ', data, flags=re.M)
The re.sub
will replace with a space any line that matches re.sub
将用空格替换任何匹配的行
^
- line start (note the flags=re.M
argument that makes sure the multiline mode is on) ^
- 行开始(注意flags=re.M
确保多行模式打开的参数)meshname
- a meshname
word meshname
- meshname
单词=
- a =
string =
- a =
字符串.*
- any zero or more chars other than line break chars as many as possible .*
- 尽可能多的除换行符以外的任何零个或多个字符\w
- a letter/digit/ _
\w
- 一个字母/数字/ _
$
- line end. $
- 行结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.