If you mean that a string must have four digits at the end, that is, the four digits are preceded by a non-digit, then you can use a positive look-behind assertion to look at the character before that group.

Since we are dealing with strings, and not lines, you should use string anchors (\A and \z). Working backwards, \d{4} gives us 4 digits. To see if the character before that is a non-digit? (?<=\D) (mnemonic: before equals a non-digit). This looks at the character, but does not consume it.

Then, alphanum characters and underscore can be represented by \w. As an added bonus (or possibly not, that's your call) it will work correctly on UTF-8 characters that represent alphanumish characters.

Putting it all together, we get

sub is_valid { my $test = shift; return $test =~ /\Aaaa_\w{1,24}(?<=\D)\d{4}\z/; }

I naturally tend to wrap this logic up in a routine , so that in the mainline code I can write

for my $str (qw(aaa_gjh1_dfgdf_0009 aaa_gjh_0000 aaa_fdsfs_000 aaa_sdf +_jdsh_01111)) { print (is_valid($str) ? "ok $str\n" : "not ok $str\n"); }

• another intruder with the mooring in the heart of the Perl


In reply to Re: Number of digits at the end of the string by grinder
in thread Number of digits at the end of the string by isha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.