我想用"quot;其以";meshname=";并以任何字母/数字和下划线组合结尾。我在CS中使用了regex,但我从未真正理解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
为了替换包含meshname=…的文件中的每一个字符串/行,脚本会是什么样子。。。使用Python正则表达式?像这样的东西?
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()
还是这完全错了?我试着用这种方法让它工作,但不知怎么的,它从来没有匹配到正确的字符串:如何在string.replacement中输入regex?
按照当前的代码逻辑,您可以使用
data = re.sub(r'^meshname = .*w$', ' ', data, flags=re.M)
re.sub
将用空格替换任何与匹配的行
^
-行开始(注意确保多行模式打开的flags=re.M
参数(meshname
-一个meshname
字=
-=
字符串.*
-除了换行字符之外的任何零个或多个字符,尽可能多w
-字母/数字/_
$
—线路端