Home > Back-end >  How can I use regex to select first six characters only when there are 12 characters present
How can I use regex to select first six characters only when there are 12 characters present

Time:04-02

I have some regex that selects the first 6 characters and last six characters. ^.{0,6} .{6}$.

I basically only want it to select the first/last 6 characters if there are 12 characters.

Eg. select nothing if 202203, but select the first six characters if 202201202203.

Is there any way to accomplish this?

Thanks

CodePudding user response:

Your pattern ^.{0,6} .{6}$ matches 0-6 characters with this part .{0,6} and matches a mandatory space before the last 6 characters which is not present in 202201202203

You can use 2 capture group instead, and then you can select if you want the first or last 6 characters.

^(.{6})(.{6})$

Regex demo

Note that the . can also match a space.

CodePudding user response:

This works if 12 characters is your minimum and maximum by using look ahead:

^.{6}(?=.{6}).{6}$
  • Related