如何在python中找到括号绑定的字符串

2024-10-03 23:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,想在网络安全课程中自动完成一项作业。 我试图找出如何查找由一组括号绑定的文件的内容。(.txt)文件的内容如下所示:

cow.jpg : jphide[v5](asdfl;kj88876)
fish.jpg : jphide[v5](65498ghjk;0-)
snake.jpg : jphide[v5](poi098*/8!@#)
test_practice_0707.jpg : jphide[v5](sJ*=tT@&Ve!2)
test_practice_0101.jpg : jphide[v5](nKFdFX+C!:V9)
test_practice_0808.jpg : jphide[v5](!~rFX3FXszx6)
test_practice_0202.jpg : jphide[v5](X&aC$|mg!wC2)
test_practice_0505.jpg : jphide[v5](pe8f%yC$V6Z3)
dog.jpg : negative`

这是我目前的代码: 你知道吗

import sys, os, subprocess, glob, shutil

# Finding the .jpg files that will be copied.
sourcepath = os.getcwd() + '\\imgs\\'
destpath = 'stegdetect'
rawjpg = glob.glob(sourcepath + '*.jpg')

# Copying the said .jpg files into the destpath variable
for filename in rawjpg:
    shutil.copy(filename, destpath)

# Asks user for what password file they want to use.
passwords = raw_input("Enter your password file with the .txt extension:")
shutil.copy(passwords, 'stegdetect')

# Navigating to stegdetect. Feel like this could be abstracted.
os.chdir('stegdetect')

# Preparing the arguments then using subprocess to run
args = "stegbreak.exe -r rules.ini -f " + passwords + " -t p *.jpg"

# Uses open to open the output file, and then write the results to the file.
with open('cracks.txt', 'w') as f: # opens cracks.txt and prepares to w
        subprocess.call(args, stdout=f)

# Processing whats in the new file.
f = open('cracks.txt')

Tags: thetotesttxtosopenglobfile
3条回答

如果它只是由(and)绑定,那么可以使用下面的regex,它可以确保开始(和结束),并且它们之间可以有数字和字符。您还可以添加任何其他要包含的符号。你知道吗

[\(][a-z A-Z 0-9]*[\)]

[\(] - starts the bracket
[a-z A-Z 0-9]* - all text inside bracket
[\)] - closes the bracket

所以对于输入sdfsdfdsf(sdfdsfsdf)sdfsdfsdf,输出将是(sdfdsfsdf) 在这里测试这个正则表达式:https://regex101.com/

I'm learning Python

如果您正在学习,您应该考虑替代实现,而不仅仅是regexp。你知道吗

要逐行迭代文本文件,只需打开该文件并覆盖文件句柄:

with open('file.txt') as f:
    for line in f:
        do_something(line)

每一行都是一个包含行内容的字符串,包括行尾字符'/n'。要查找字符串中特定子字符串的起始索引,可以使用find:

>>> A = "hello (world)"
>>> A.find('(')
6
>>> A.find(')')
12

要从字符串中获取子字符串,可以使用以下形式的切片表示法:

>>> A[6:12]
'(world'

您应该使用在Python re module中实现的正则表达式

\(.*\)这样的简单正则表达式可以匹配您的“括号字符串” 但是使用组\((.*)\)会更好,它只允许获取括号中的内容。你知道吗

import re

test_string = """cow.jpg : jphide[v5](asdfl;kj88876)
fish.jpg : jphide[v5](65498ghjk;0-)
snake.jpg : jphide[v5](poi098*/8!@#)
test_practice_0707.jpg : jphide[v5](sJ*=tT@&Ve!2)
test_practice_0101.jpg : jphide[v5](nKFdFX+C!:V9)
test_practice_0808.jpg : jphide[v5](!~rFX3FXszx6)
test_practice_0202.jpg : jphide[v5](X&aC$|mg!wC2)
test_practice_0505.jpg : jphide[v5](pe8f%yC$V6Z3)
dog.jpg : negative`"""

REGEX = re.compile(r'\((.*)\)', re.MULTILINE)

print(REGEX.findall(test_string))
# ['asdfl;kj88876', '65498ghjk;0-', 'poi098*/8!@#', 'sJ*=tT@&Ve!2', 'nKFdFX+C!:V9' , '!~rFX3FXszx6', 'X&aC$|mg!wC2', 'pe8f%yC$V6Z3']

相关问题 更多 >