Python 正则表达式匹配/组

Python 正则表达式匹配/组,python,regex,match,Python,Regex,Match,我一直在努力学习自动分段,所以我在github上找到了一个代码,但我不明白为什么它不能运行。我不明白rs=re.match('.+',str(p))当我运行这一行时,它会得到一个匹配,然后转到patient_images[file][rs.groups()[0]]=p,但随后我得到错误indexer:tuple index超出范围。我打印出rs,得到None。为什么我的没有 图像目录的结构如下所示: code: patients: pat01: i

我一直在努力学习自动分段,所以我在github上找到了一个代码,但我不明白为什么它不能运行。我不明白
rs=re.match('.+',str(p))
当我运行这一行时,它会得到一个匹配,然后转到
patient_images[file][rs.groups()[0]]=p
,但随后我得到错误
indexer:tuple index超出范围
。我打印出
rs
,得到
None
。为什么我的
没有

图像目录的结构如下所示:

code:
    patients:
        pat01:
            images:
                export1.dcm
                export2.dcm
                export3.dcm
            masks:
                export1.dcm
                export2.dcm
                export3.dcm
代码:

对于
rs=re.match(…)
您需要
rs.group()
(注意没有“s”)作为匹配字符串的一部分

此外,“+”的正则表达式将匹配至少有一个字符的所有字符串,因此更便于编写:

p=os.path.join(根目录,文件)
如果len(p)>0:
患者图像[文件][p]=p

我刚刚注意到,
。+”
是我为了使代码正常工作而进行的编辑。原始字符串是
rs=re.match('.*masks/(.*)/.*',str(p))
rs的输出是
None
。啊,太酷了。该正则表达式的输出为None,因为它与字符串不匹配。您的路径是“pat01/masks/export1.dcm”,但regex需要“masks/something/something\u other”
import os, re

root_dir = f"C:/Users/user/Desktop/code/patients/"
patient_images = {}
for root, dirs, files in os.walk(root_dir):
    for file in files:
        if file.endswith('.dcm'):
            if 'PATIENT_DICOM' in root:
            if not patient_images.get(file,None):
                patient_images[file] = {}
            p = os.path.join(root,file)
            patient_images[file]['real'] = p

            elif 'masks' in root:
                print(os.path.join(root,file))
                if not patient_images.get(file,None):
                    patient_images[file] = {}
                p = os.path.join(root,file)
                rs = re.match('.*MASKS_DICOM/(.*)/.*', str(p))
                if rs:
                    patient_images[file][rs.groups()[0]] = p
                    print('match')
                else:
                    print('Did not match groups')