당신은 아마 이것에 대한 하나의 복잡한 정규식을 생각해 낼 수 있습니다.하지만 각 섹션을 왼쪽에서 오른쪽으로 떼어 내면 코드를 읽는 것이 훨씬 쉬울 것입니다. 다음은 그냥 않는 일부 파이썬 코드 :
lines = ["DISK1:[MYROOT.][MYDIR]FILE.DAT", "DISK1:[MYDIR]FILE.DAT", "[MYDIR]FILE.DAT", "FILE.DAT;10", "NODE::DISK5:[REMOTE.ACCESS]FILE.DAT"]
node_re = "(\w+)::"
device_re = "(\w+):"
root_re = "\[(\w+)\.]"
dir_re = "\[(\w+)]"
file_re = "(\w+)\."
type_re = "(\w+)"
version_re = ";(.*)"
re_dict = {"node": node_re, "device": device_re, "root": root_re, "directory": dir_re, "file": file_re, "type": type_re, "version": version_re}
order = ["node", "device", "root", "directory", "file", "type", "version"]
for line in lines:
i = 0
print line
for item in order:
m = re.search(re_dict[item], line[i:])
if m is not None:
print " " + item + ": " + m.group(1)
i += len(m.group(0))
및 출력은
위키 피 디아에서
DISK1:[MYROOT.][MYDIR]FILE.DAT
device: DISK1
root: MYROOT
directory: MYDIR
file: FILE
type: DAT
DISK1:[MYDIR]FILE.DAT
device: DISK1
directory: MYDIR
file: FILE
type: DAT
[MYDIR]FILE.DAT
directory: MYDIR
file: FILE
type: DAT
FILE.DAT;10
file: FILE
type: DAT
version: 10
NODE::DISK5:[REMOTE.ACCESS]FILE.DAT
node: NODE
device: DISK5
directory: REMOTE.ACCESS
file: FILE
type: DAT
위 예의 "[]"대괄호 안에있는 텍스트도 선택적입니까? "MYROOT.", "MYDIR"및 "REMOTE.ACCESS"가 별칭입니까? 아니면 문자열 리터럴입니까? –
내가 알 수있는 한, 대괄호는 쓰레기이며 선택적이 아닙니다. 허용 된 디렉토리 이름 및 문자에 대한 정확한 스펙을 찾지 못했습니다. 사양에서 나의 이해는 디렉토리 이름은 STRING으로 식별됩니다. STRING – bengrine
또한 각 디렉토리 이름과 파일 이름은 9 자 이하로 제한됩니다. 노드와 장치에도 길이 제한이 있습니다 (그러나 그 내용은 기억이 안납니다). –