0

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.

4

3 回答 3

4

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.

于 2013-03-08T19:15:34.533 回答
1

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)*)/
于 2013-03-08T19:19:08.747 回答
0

\w包括字母、数字和下划线。

所以你可以使用像这样简单的东西: /ABCD\w+/

于 2013-03-08T19:24:56.833 回答