首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >匹配endwith python

问匹配endwith python
EN

Stack Overflow用户
提问于 2017-06-02 16:13:23
回答 1查看 362关注 0票数 0

实际的endswith字符串如下:

代码语言:javascript
复制
 RP/0/RSP0/CPU0:asr1#

我在代码中用来检查endswith是

代码语言:javascript
复制
#

代码如下:

代码语言:javascript
复制
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

即使我用"#“来检查endswith,一切都很正常,但我想在这里再检查一遍。是我做得对,还是我们有其他更好的选择来实现这一点

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

代码语言:javascript
复制
 "RP/" is constant 

如何使用它是匹配

代码语言:javascript
复制
 "RP/anything#"
EN

回答 1

Stack Overflow用户

发布于 2017-06-02 17:09:30

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

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

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

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

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

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

对于您的问题,有一个示例:

代码语言:javascript
复制
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的正则表达式模块。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44323973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档