merkle
merkle

Reputation: 1815

Regex match the characters with same character in the given string

I am working on validating the pan card numbers. I need to check that the first character and the fifth character should be same while validating the pan card. Whatever the first character in the below string the same should be matched with the fifth character. Can anyone help me in applying the above condition?

Regex I have tried : [A-Za-z]{4}\d{4}[A-Za-z]{1}

Here is my pan card example: ABCDA9999K

Upvotes: 0

Views: 53

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

If you want to match the full example string where the first A should match up with the fifth A, the pattern should match 5 occurrences of [A-Za-z]{5} instead of [A-Za-z]{4}

You could use a capturing group with a backreference ([A-Za-z])[A-Za-z]{3}\1 to account for the first 5 chars.

You might add word boundaries \b to the start and end to prevent a partial match or add anchors to assert the start ^ and the end $ of the string.

This part of the pattern {1} can be omitted.

([A-Za-z])[A-Za-z]{3}\1\d{4}[A-Za-z]

Regex demo

Upvotes: 2

Related Questions