Match portion of a capture group with Perl Regex

60 Views Asked by At

I have a datafile with a structure such as:

FNAME:LNAME:USERNAME

I am trying to go through and check if the format is valid for each line of this data file by using regex.

The way I want to do it is as follows except I am unsure how to set up the expression for the username portion.

if(/([A-Z]):([A-Z]):_______/)

$1 will give the entire first name, $2 will give the entire last name. the username is comprised of the first letter of the first name and the first four of the last name. I am unsure how I could check this with capture groups. Is there a way for me to check only a portion of $1 and $2 without making variables outside of the regex expression itself?

1

There are 1 best solutions below

2
On

How about something like

/^([A-Z])[A-Z]+:([A-Z]{4})[A-Z]+:\1\2$/
  • ([A-Z]) First caputure group. Contains the first character from the FNAME

  • [A-Z]+ Matches the rest characters

  • ([A-Z]{4}) Second characters. Contains 4 characters from LNAME

  • [A-Z]+ Matches the rest characters

  • \1\2 Contents of first and second capture group forms the USERNAME part