from typing import Optional
from typing import Pattern
import re


def factorByCaptureFun(
    name: Optional[str], pat: Pattern[str], default: Optional[str] = None
) -> Optional[str]:
    """
    Determine a tip factor using regular expression capture.

    Patterns may be nested, for example `(swine.(...)|human.(..))`.
    Internally, python collects matches in a flat tuple with positions ordered
    by opening parenthesis. So the string "swine|USA" would return
    `("swine|USA", "USA", None)`. The last None is because the human pattern
    matched nothing. The smot convention is to take the last pattern that
    matched. In this case, "USA".
    """
    if name is not None:
        m = re.search(pat, name)
        if m and m.groups():
            return [x for x in list(m.groups()) if x is not None][-1]
    return default