[問題] python正規表示式如何做?

看板Python作者 (賣雞排的少年)時間6年前 (2018/11/07 22:09), 6年前編輯推噓1(1017)
留言18則, 8人參與, 6年前最新討論串1/1
In [1] tmp.content Out [1] b'[\n{"_id":"DUT2236-bkcin128-11032016","InternetGatewayDevice": {"DeviceInfo":{"SWV":{"_object":false,"_value":"0.02.01", "_type":"xsd:string","_timestamp":"2018-11-07T13:47:17.373Z","_writable":false}}}}\n]' 現在我的程式碼如下: import re In [1] test_string = 'find: tmp.content' pattern = 'DeviceInfo | SWV | 0.02.01' ans=re.findall(pattern,test_string) print(ans) Out [1] [] 出現的結果為空? 為何在Out [1] 沒有出現DeviceInfo.SoftwareVersion 0.02.01的訊息? 想請問一下,我是少做了甚麼? 懇請指點<(_ _)> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.224.53.188 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1541599781.A.983.html ※ 編輯: han999 (36.224.53.188), 11/07/2018 22:13:02

11/07 22:15, 6年前 , 1F
| 這個符號應該要escape 我猜啦
11/07 22:15, 1F

11/07 22:15, 6年前 , 2F
空格改用\s看看
11/07 22:15, 2F

11/07 22:15, 6年前 , 3F
你有看過文件?
11/07 22:15, 3F

11/07 22:16, 6年前 , 4F
然後你應該print test_string看是什麼
11/07 22:16, 4F

11/07 22:34, 6年前 , 5F
大概是少看了re.findall的文件
11/07 22:34, 5F

11/07 22:38, 6年前 , 6F
資料一看就是 json ,為何不用 json.loads ?
11/07 22:38, 6F

11/07 22:50, 6年前 , 7F
import json;_j = json.loads(tmp.content)
11/07 22:50, 7F

11/07 22:52, 6年前 , 8F
print(_j[0]['DeviceInfo']['SWV']['_value'])
11/07 22:52, 8F

11/07 22:53, 6年前 , 9F
re 的用法找一下吧 ,語法錯誤甚至不知道你要切啥...
11/07 22:53, 9F

11/07 22:58, 6年前 , 10F
更正一下上面的 key ['InternetGatewayDevice']['DeviceI
11/07 22:58, 10F

11/07 22:58, 6年前 , 11F
... 後略,資料隔是既然是 json 用 json.loads 就會
11/07 22:58, 11F

11/07 22:58, 6年前 , 12F
很原味的轉成 python 的內建類別了
11/07 22:58, 12F

11/07 22:59, 6年前 , 13F
當然若是遇到一些空值或編碼,要加點 flag 去調整
11/07 22:59, 13F

11/08 09:04, 6年前 , 14F
'DeviceInfo | SWV | 0.02.01',把中間的空格刪掉。
11/08 09:04, 14F

11/08 09:07, 6年前 , 15F
這個網站https://regex101.com/ 或 Notepad++進行測試
11/08 09:07, 15F

11/08 22:15, 6年前 , 16F
'find: tmp.content' ??? 所以這是一整個字串?
11/08 22:15, 16F

11/09 06:54, 6年前 , 17F
test_string改成f'find: {tmp.content}'看看
11/09 06:54, 17F

11/11 11:25, 6年前 , 18F
感覺起來test_string是一般字元而不是檔案內容
11/11 11:25, 18F
文章代碼(AID): #1Rul8bc3 (Python)
文章代碼(AID): #1Rul8bc3 (Python)