【问题标题】:Matching endwith python匹配以python结尾
【发布时间】:2017-06-02 08:13:22
【问题描述】:

我正在使用 paramiko 进行 ssh 并等待正在检查字符串结尾的提示。

实际结尾的字符串如下:

 RP/0/RSP0/CPU0:asr1#

我在代码中使用检查endswith是

#

下面是代码:

import paramiko
import re
import time
hostname = "10.10.10.10"
net_username = "user"
net_password = "password"
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(
     paramiko.AutoAddPolicy())
remote_conn_pre.connect(hostname, username=net_username, password=net_password,look_for_keys=False, allow_agent=False)
remote_conn = remote_conn_pre.invoke_shell()
buff = ''
while not buff.endswith('#'):
    resp = remote_conn.recv(9999)
    buff += resp
    print(resp)
remote_conn.send("\n")
buff = ''
while not buff.endswith('#'):
    resp = remote_conn.recv(9999)
    buff += resp
    print(resp)
remote_conn.send("ping 172.16.35.22\n")
time.sleep(2)
buff = ''
while not buff.endswith('#'):
    resp = remote_conn.recv(9999)
    buff += resp
    print resp

即使我使用“#”检查结尾,一切正常,但我想在这里仔细检查。我这样做是正确的还是我们有其他更好的选择来实现这一目标

我的意思是结尾是字符串“RP/0/RSP0/CPU0:asr1#”。

 "RP/" is constant 

如何使用它来匹配

 "RP/anything#"

【问题讨论】:

  • re.compile(r"(RP/[a-z]*#{1})") 这不是最好的。但它可以帮助你

标签: python regex python-2.7 paramiko


【解决方案1】:

如果你想使用 python 的regular expression module 来增强你​​的搜索:

您必须使用re.match 将您的正则表达式与您的字符串匹配:

re.match(pattern, string, flags=0)

如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的 MatchObject 实例。如果字符串与模式不匹配,则返回 None;请注意,这与零长度匹配不同。

请注意,即使在 MULTILINE 模式下,re.match() 也只会匹配字符串的开头,而不是每行的开头。

如果您想在字符串中的任何位置找到匹配项,请改用 search()(另请参阅 search() 与 match())。

您的问题有一个示例:

import re # module for regular expression

string = "RP/0/RSP0/CPU0:asr1#"
match = re.match(r"^RP/[(\d|\w)|(/|:)]*#{1}$", string)
if (match):
    # The string match with the regular expression
else:
    # The string doesn't match the regular expression

如果你不知道如何使用正则表达式并想练习它们,你可以使用这个网站:regex101.com。这个网站也有python的正则表达式模块。

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2021-01-21
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多