我在下面的代码片段中搜索wordkoint,但是它会打印所有相关的单词,比如koint
、koint_local
和koint_limited
。你知道吗
除了regex之外,是否有一种严格的方法来查找这类需求中的字符串/单词。你知道吗
from subprocess import Popen, PIPE
CRED = '\033[91m'
CGRN = '\033[92m'
CEND = '\033[0m'
with open("kkdiff", "r") as lid:
for line in lid:
line = line.strip()
proc = Popen(['id', line], stdout=PIPE,)
myID = proc.communicate()[0].decode('utf-8')
if 'koint' in myID:
print(line, CGRN + "Success: " + CEND + "User exists in the Group")
else:
print(line, CRED + "Failed: " + CEND + "User does not exists in the Group")
当我只查找koint
时,上面的代码段返回如下:
user1 Failed: User does not exists in the Group
user30 Success: User exists in the Group (<-- koint_local)
user81 Success: User exists in the Group (<-- koint_limited)
Raw data in myID:
uid=24699(user1) gid=1001(skilla) groups=1786(koint),1614(koint_limited),101(torr)
在上面的数据中,即使koint
缺失并且koint_limited
存在,也表示成功。你知道吗
要求:如果在行中找到koint
,则打印成功。你知道吗
正如我在文章开头提到的,除了regex: 尽管正则表达式有效:
from subprocess import Popen, PIPE
CRED = '\033[91m'
CGRN = '\033[92m'
CEND = '\033[0m'
with open("kkdiff", "r") as lid:
for line in lid:
line = line.strip()
proc = Popen(['id', line], stdout=PIPE,)
myID = proc.communicate()[0].decode('utf-8')
if re.search(r'\bkoint\b', myID):
print(line, CGRN + "Success: " + CEND + "User exists in the Group")
else:
print(line, CRED + "Failed: " + CEND + "User does not exists in the Group")
我已经编译了工作代码,所以它可能是有用的人看所以。现在有两种有
regex
和没有regex
的解决方案。你知道吗1)不含
regex
2)基于
regex
将字符串与完整单词koint匹配的正则表达式
Regular Expression Syntax
看起来
groups
命令更适合您的需要。你知道吗相关问题 更多 >
编程相关推荐