1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Regular expressions.

Discussion in 'CIW Certifications' started by stuPeas, Oct 2, 2007.

  1. stuPeas

    stuPeas Megabyte Poster

    774
    12
    76
    I honestly thought I knew this stuff, but then I come to revise I find I actualy was clueless. There is some example code to illustrate.

    Its Perl BTW.

    Code:
    $myString = "adcd";
    
    if ($myString =~ m/\w{1,3}/){
    
       print("your pattern matches $myString");
    } 
    
    Now here's what I thought I knew. The characters {1,3} will match the string as long as the string contains 1 letter and NO MORE THAN 3 letters. Im obviously wrong because the code above actualy matches.

    Can somone tell me what im doing wrong please.
    Cheers.
    Stu.
     
    Certifications: C&G Electronic, CIW Associate (v5).
    WIP: CIW (Website Design Manager)
  2. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,623
    115
    224

    It is matching on the first 3 characters. Put '$' at the end of the match string to stop it matching longer strings.

    Edit: <cough> and of course a '^' at the start, otherwise it will match the last 3 characters!

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  3. stuPeas

    stuPeas Megabyte Poster

    774
    12
    76
    I'm paying too much attention to my course manual again. It is worded VERY badly, here is what it says regarding {1,4}

    "must match at least once but no more than four times".

    I take this to mean that if you have a string of five letters, then the match will fail. God I wish I'd self studied. In fact, with the manual being wrong about 90% of the time, I more or less HAVE.

    Cheers Harry :D
     
    Certifications: C&G Electronic, CIW Associate (v5).
    WIP: CIW (Website Design Manager)
  4. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,623
    115
    224
    Actualy - it is right - but it depends on how you read it!

    Because matching is 'greedy' it will start by attempting to match 4 times. If you have a string with more than 4 characters in it it will match - it has found 4 characters. It doesn't care that there are more characters afterwards.

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+

Share This Page

Loading...