2016-04-27 16 views
0
尋找一個特定的詞

我的輸出是如何使用正則表達式,如果我在整個字符串

Select action => test: username, status 1 

我試圖做如果「用戶名」字符串存在,則繼續執行代碼,否則打印失敗,並退出

如果我寫p.expect('*username*')返回錯誤

raise error, v # invalid expression 
sre_constants.error: nothing to repeat 

這是衆所周知的python我猜錯誤。

在這種情況下,最好的方法是什麼?

+0

如果您不需要全字搜索,使用下面答案中的那個。 –

+0

我使用https://regex101.com/來幫助我瞭解和編寫正則表達式代碼。 –

+0

檢查_username_是否存在將會非常棘手。它可能會有拼寫和對齊的變化,實際上可能是一種顏色,即約翰布朗的大日子。你完全錯過了。最重要的是大小寫,無論是第一還是最後,或者兩者兼而有之。這類似於解析語言,這對於正則表達式來說是不可能的。 – sln

回答

2

爲什麼使用這個正則表達式?如果你只是看到如果子是在一個字符串只是用

if `username` in some_string: 
    #exec more code. 
+0

事情是我正在運行python腳本併發送命令到我的設備。它在設備上創建日誌文件,我試圖查看該日誌文件中是否存在用戶名。因此如果用戶名在log.txt中不能使用 –

+0

你可以。 '如果用戶名在[x.strip()for open in(「log.txt」,「r」)。readlines()]'儘管你可能不想像這樣打開文件,你可以調整以適合需要。只是一個隨機的例子,以適應註釋 – Pythonista

0

如果你是使用正則表達式出於某種原因意圖:

import re 
output = "Select action => test: username, status 1" 

UserNameRegEx = re.search('username',output) #RegEx to search for the string "username" in string "output". Stores as an object. 

#if regEx object UserNameRegEx exists (meaning that a match was found) 
if match_module_present:   
    username = UserNameRegEx.group(1) #assigns the matched string from regex object to a string variable 
    #run more code 
+0

如果我知道輸出字符串,這可能是可變的。在我的情況下,我正在我的設備上執行一些用戶活動並嘗試讀取控制檯輸出。 Python腳本從我的電腦中調用,設備是基於Unix的 –

相關問題