user1985039
user1985039

Reputation: 21

Pattern matching in Perl

I am doing pattern match for some names below:

ABCD123_HH1
ABCD123_HH1_K

Now, my code to grep above names is below:

($name, $kind) = $dirname =~ /ABCD(\d+)\w*_([\w\d]+)/; 

Now, problem I am facing is that I get both the patterns that is ABCD123_HH1, ABCD123_HH1_K in $dirname. However, my variable $kind doesn't take this ABCD123_HH1_K. It does take ABCD123_HH1 pattern.

Appreciate your time. Could you please tell me what can be done to get pattern with _k.

Upvotes: 0

Views: 93

Answers (3)

alestanis
alestanis

Reputation: 21863

You need to add the _K part to the end of your regex and make it optional with ?:

/ABCD(\d+)_([\w\d]+(_K)?)/

I also erased the \w*, which is useless and keeps you from correctly getting the HH1_K.

Upvotes: 4

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4526

\w includes letters, numbers as well as underscores.

So you can use something as simple as this: /ABCD\w+/

Upvotes: 0

Krishnachandra Sharma
Krishnachandra Sharma

Reputation: 1342

You should check for zero or more occurrences of _K.

* in Perl's regexp means zero or more times

+ means atleast one or more times.

Hence in your regexp, append (_K)*.

Finally, your regexp should be this:

/ABCD(\d+)\w*_([\w\d]+(_K)*)/

Upvotes: 1

Related Questions