import re


def regex_first_claim(fullclaim, maxlen):
  """Attempts to extract the first patent claim from the full set of claims.

  Because patent claims have predictable strcuture, we can attempt to extract
  the first claim based on a few rules. If none of these work, we return all
  characters up to `maxlen`.

  Args:
    fullclaim: A string containing the full text of a patents claims.
    maxlen: An upper limit on the size of the result. This limit is only used if
      all previous extraction methods fail.
  Returns:
    A string containing the best estimate of the text of the first.
  """
  # First try the simplest - split on the text '2.' or '2 .'.
  split_on_2 = re.split(r'.\s+[2]\s*.', fullclaim)
  if len(split_on_2) > 1:
    return split_on_2[0]

  # Next split on the first reference to 'claim 1'.
  if 'claim 1' in fullclaim.lower():
    return fullclaim.split('claim 1')[0]

  # If none of the above worked, split on The (case sensistive). This word
  # should only appear in dependent claims by convention.
  if ' The ' in fullclaim:
    return fullclaim.split(' The ')[0]

  # Finally, just keep the first N chars based on maxlen input.
  return fullclaim[:maxlen]