SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regex match exactly

    I have this regex:

    ^\\d{4}

    to see if the string matches 4 digits, but it to ONLY match 4 digits ie:

    1234 matches

    1234gh does not.

    cheers
    monkey - the rest is history

  2. #2
    Chopped Liver bronze trophy imaginekitty's Avatar
    Join Date
    Aug 2007
    Location
    Pennsyltucky
    Posts
    1,494
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    ^\d{4}$

  3. #3
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by imaginekitty View Post
    ^\d{4}$
    if (Regex.IsMatch(r, "^\d{4}"))

    this caused the d to be highlighted by VS as 'Unrecognised escape sequence'
    monkey - the rest is history

  4. #4
    SitePoint Guru Jason__C's Avatar
    Join Date
    Oct 2009
    Location
    Racoon City
    Posts
    658
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You forgot the "$" sign...

  5. #5
    SitePoint Mentor NightStalker-DNS's Avatar
    Join Date
    Jul 2004
    Location
    Cape Town, South Africa
    Posts
    2,869
    Mentioned
    38 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    if (Regex.IsMatch(r, @"^\d{4}$"))

  6. #6
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by NightStalker-DNS View Post
    Try this:

    if (Regex.IsMatch(r, @"^\d{4}$"))
    cheers - that did it! What does the @ do then?
    monkey - the rest is history

  7. #7
    SitePoint Wizard
    Join Date
    Feb 2007
    Posts
    1,274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by boxhead View Post
    cheers - that did it! What does the @ do then?
    The @ makes the string a verbatim string. In a verbatim string \ (backslash) is literal and not an escape character which alters the meaning of the following char.

    If the string had not been literal you would have needed to put in two \\s to make one \.

    The regular expression is still ^\d{4}$ - it is just how to represent it in a string.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •