import re


def _ParseOutputSpec(output_spec):
    """Parses the output spec.

    Args:
      output_spec: Output layer definition. See Build.

    Returns:
      out_dims:     2|1|0 for 2-d, 1-d, 0-d.
      out_func:     l|s|c for logistic, softmax, softmax+CTC
      num_classes:  Number of classes in output.

    Raises:
      ValueError: if syntax is incorrect.
    """
    pattern = re.compile(R'(O)(0|1|2)(l|s|c)(\d+)')
    m = pattern.match(output_spec)
    if m is None:
        raise ValueError('Failed to parse output spec:' + output_spec)
    out_dims = int(m.group(2))
    out_func = m.group(3)
    if out_func == 'c' and out_dims != 1:
        raise ValueError('CTC can only be used with a 1-D sequence!')
    num_classes = int(m.group(4))
    return out_dims, out_func, num_classes