我正在尝试在 Python 中搜索给定字符串模式的目录。然后我想将匹配项组装到一个数组中。
起初,我尝试使用 grep:
regex = " dojo.require(..*) "
bashCommand = "grep"+" --only-matching -r -h"+regex+baseDir
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
dirStr = process.communicate()[0]
但我意识到我需要支持多行字符串,例如
dojo.require(
"abc"(;
所以 grep 不是一个选项。
还有哪些其他方法可以实现此目的?提前致谢。
最佳答案
您可以使用 os 的组合在纯 Python 中实现此功能,而不是调用 grep和 re 。使用re.DOTALL允许多行匹配的标志。例如:
import re, os
def grep(regex, base_dir):
compiled_regex = re.compile(regex, re.DOTALL)
matches = list()
for filename in os.listdir(base_dir):
full_filename = os.path.join(base_dir, filename)
if not os.path.isfile(full_filename):
continue
with open(os.path.join(base_dir, filename)) as fh:
content = fh.read()
if compiled_regex.search(content):
matches.append(full_filename)
return matches
print grep(" dojo.require(..*) ", ".")
关于python - 搜索目录中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042592/