import re


def extract_bids_identifier_from_caps_filename(caps_dwi_filename):
    """Extract BIDS identifier from CAPS filename."""

    m = re.search(r"(sub-[a-zA-Z0-9]+)_(ses-[a-zA-Z0-9]+).*_dwi", caps_dwi_filename)

    if m is None:
        raise ValueError("Input filename is not in a CAPS compliant format.")
    bids_identifier = m.group(0)

    return bids_identifier