SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: Regex help

  1. #1
    SitePoint Addict inverse.chi's Avatar
    Join Date
    May 2006
    Location
    Oxford, UK | Durham, UK
    Posts
    243
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex help

    Hi,

    I want to be able to write a regular expression that matches whole and decimal numbers as well as negatives, however there's a few problems with what i have so far and that is that it matches -0 when i want it to not match that. how would i resolve this? also it allows numbers like 038.48 to be added

    ^(-|)(\d+[.]\d+|0|\d+)$

    thanks in advance
    Last edited by inverse.chi; Aug 19, 2008 at 06:15.
    Malachi Soord
    Something will come here

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,097
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    ^-?\d*\.?\d*$

  3. #3
    SitePoint Addict inverse.chi's Avatar
    Join Date
    May 2006
    Location
    Oxford, UK | Durham, UK
    Posts
    243
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi thank you for replying, however that still matches -0 and numbers such as 029 038.9 and 1.0
    Malachi Soord
    Something will come here

  4. #4
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,097
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    Okay,

    Try this: ^-?(?!0)[0-9]*\.?\d*$


    The (?!) is called the "Nagative Lookahead", it says that the character defined here may not be the next character in the string (so, the 0 in this case). It prevents numbers like -0 or 0123

    Edit:


    This still matches 1.0, but I'm not sure how to avoid this. Just asserting the first character after the decimal cannot be a 0 doesn't help, because that would also exclude 1.01
    Maybe catch this in your scripting language

    if ((int)$num == $num) $num = (int)$num;

    to cast it to an integer

  5. #5
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Code:
    ^([-+]?[1-9]\d*(?:\.(?:[1-9]|\d+[1-9]))?)$
    Could probably improve on it by using look arounds.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.



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
  •