首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >搜索包含数字的字符串python

搜索包含数字的字符串python
EN

Stack Overflow用户
提问于 2018-08-01 03:52:33
回答 2查看 871关注 0票数 1

所以我有以下代码:

代码语言:javascript
复制
cus_str = "show configuration " #intiate router command string variable

with open(var) as config_file: #open file
    for line in config_file: #line by line reading of file
        if '"xe-" + #anynumber + "/" #anynumber + "/" + #anynumber' in line:
            line = line.replace('\n' , '').replace('"' , '').replace(']' , '')     #removes all extra characters
            i = "| except " + (line.split("cust ", 1)[1]) + " " #split the line and save last index (cust name)
        cus_str+=i #append to string
config_file.close()

这一行: if '"xe-“+ #anynumber + "/”#anynumber + "/“+ #anynumber‘in line:就是我在语法方面遇到的问题。

我正在查看文件中的某一行是否包含以下字符串:"xe-number/number/number“(例如:"xe-6/1/10")。它将始终具有此格式,但数字将发生变化。我应该使用哪种语法来最有效地实现这一点。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-01 04:02:31

为此,您可以使用正则表达式。正则表达式允许您指定文本模式(尽管并非所有模式都可以表示为正则表达式)。然后,我们可以将该表达式compile到一个Pattern对象中,并使用该对象为模式search字符串。

代码语言:javascript
复制
import re

pattern = re.compile(r'"xe-\d+/\d+/\d+"')  # \d+ is "one or more digits".  
                                           # Everything else is literal

with open(var) as config_file:
    for line in config_file:
        if pattern.search(line):  # will return a Match object if found, else None
            ...
票数 3
EN

Stack Overflow用户

发布于 2018-08-01 04:09:15

你可以用一个简单的程序测试一个正则表达式,就像用https://pythex.org/这样的在线工具,然后制作你的程序,一个正确的方向的小示例将会是:

代码语言:javascript
复制
import re

config_file = ["xe-6/1/10", "xf-5/5/542", "xe-4/53/32" ]
rex = re.compile(r'xe-[\d]+/[\d]+/[\d]+')
for line in config_file: #line by line reading of file
    if rex.search(line):
      print(line)

xe-6/1/10
xe-4/53/32
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51621069

复制
相关文章

相似问题

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