import re


def seq2alignseq(seq, cigar):
    """
    Args:
        seq (str): SEQ string of SAM
        cigar (str): CIGAR string of SAM

    Returns:
        str: aligned query sequence

    Examples:
        >>> seq2alignseq(seq='TACAGCAGACGGGACCTTTTTGGTA', cigar='3S20M2S')
        'AGCAGACGGGACCTTTTTGG'
    """
    ops = [
        (k, int(v)) for k, v in zip(
            re.sub(r'[0-9]', '', cigar),
            re.split('M|I|D|N|S|H|P|=|X', cigar)[:-1]
        )
    ]
    aligned_seq = seq
    for k, v in ops:
        if k in 'ISHP':
            aligned_seq = aligned_seq[v:]
        else:
            break
    for k, v in reversed(ops):
        if k in 'ISHP':
            aligned_seq = aligned_seq[:-v]
        else:
            break
    return aligned_seq