![](/img/trans.png)
[英]Regular expression in python to get the last occurence of a file extension in a URL or path
[英]Implement regular expression in Python to replace every occurence of "meshname = x" in a text file
我想用“”替換文本文件中的每一行,它以“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()
或者這是完全錯誤的? 我試圖讓它使用這種方法,但不知何故它從未匹配正確的字符串: 如何在 string.replace 中輸入正則表達式?
按照當前的代碼邏輯,您可以使用
data = re.sub(r'^meshname = .*\w$', ' ', data, flags=re.M)
re.sub
將用空格替換任何匹配的行
^
- 行開始(注意flags=re.M
確保多行模式打開的參數)meshname
- meshname
單詞=
- a =
字符串.*
- 盡可能多的除換行符以外的任何零個或多個字符\w
- 一個字母/數字/ _
$
- 行結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.