Home > Enterprise >  How to prevent regex ^(a)?$ from capturing empty line?
How to prevent regex ^(a)?$ from capturing empty line?

Time:08-27

My goal is to regex a multiline string. The problem is that it captures empty line.

The regex: ^(a)?$

The string:

a

The result:

Match 1 a
Group 1 a
Match 2 null
Group 1 null

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex in golang to prevent this behavior:

^(?:([a-z] )|. )$

This will match & capture 1 of lowercase characters or else match any 1 char but don't allow empty match.

RegEx Demo

  • Related