Fix the case when the first group contains newline.
Fix the case when the first group contains newline.

This change also adds test cases for trailing newlines for Java and Python.

PiperOrigin-RevId: 354647044

google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research,google-research/google-research