import re


def get_master_names(desired_master_state, name_regex):
  """Returns masters found in <desired_master_state> that match <name_regex>.

  Args:
    desired_master_state: A "desired_master_state" object, e.g. as returned by
        desired_state_parser

  Returns:
    [str1, str2, ...] All masters found in <desired_master_state>
  """
  # Modify regex to allow for optional "master." prefix
  name_regex = r'(master\.)?' + name_regex
  master_matcher = re.compile(name_regex)
  return [m for m in desired_master_state["master_states"].keys()
                 if master_matcher.match(m)]