Pepe S
Pepe S

Reputation: 65

How can I use regex to select first six characters only when there are 12 characters present

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

Upvotes: 0

Views: 148

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

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.

Upvotes: 1

VvdL
VvdL

Reputation: 3210

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

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

Upvotes: 0

Related Questions