在python中进行Particula字符串搜索

时间:2014-12-22 11:18:34

标签: python string

if 'bl1' in open('/tmp/ch.py').read():
        print 'OK'

我必须搜索特定的字符串"bl1"。 有什么方法可以得到它吗?

我尝试使用^bl1$,但它没有用。

1 个答案:

答案 0 :(得分:0)

如果您只是运行验证以确认文件文本中出现“bl1”,我认为您的陈述没问题。它已经过测试,if语句返回True(假设ch.py​​里面包含'bl1'字样)......

if 'bl1' in open('/tmp/ch.py').read():
    print 'OK'

>>> if 'bl1' in open('/tmp/ch.py').read():
...     print("ok")
...
ok

>>> if 'bl1' in "dfdsaflj hjjfadsfbl1dafdsfd bl1llll bdasbl1aa":
...     print("ok")
...
ok

从你这里说'^ bl1 $',我假设你正在尝试应用正则表达式,但不幸的是你没有明确遵循正则表达式的规则。

如果您要提取包含3个连续字符'bl1'的单词,您可以应用re模块中的内置函数。

>>> import re
>>> match = re.findall('\w+[bl1]\w+', open('/tmp/ch.py').read())  // finds all occurrences 
>>> match
['asfdbl1', 'bl123']    // return all occurrences of words containing 'bl1' in a list

与格式一样,它应如下所示:

>>> if re.findall('\w+[bl1]\w+', open('/tmp/ch.py').read()):
...     print('OK')
...
OK
>>>

在正则表达式中,'^ bl1 $'是在字符串中查找一个匹配的格式,以“bl1”开头并以“bl1”结尾,这意味着整个字符串必须是'bl1'才能完全匹配..

>>> match = re.findall('^bl1$', open('/tmp/ch.py').read())
>>> match
[]
>>> match = re.findall('^bl1$', 'bl1')    // exactly "bl1"
>>> match
['bl1']
>>> match = re.findall('^bl1$', 'bl12')    // not exactly "bl1"
>>> match
[]

如果您对正则表达式感兴趣,我希望您能在Python标准库的文档中找到您喜欢的内容 - re:https://docs.python.org/3.4/library/re.html

相关问题