SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regex "digit-digit"

    Hi,

    I am trying to create regex that will parse digits input like: digit1 - digit2 OR digit1 - digit2,digit3 - digit4,digit5 - digit6,digit7 - digit8......
    With examples:

    ex1. 1-3
    ex2. 1-3,5-7
    ex3. 1-3,5-7,10-15
    ex4. 1-3,7-10,12-15,19-25
    ...

    Please note that last char should not be "," and there should not be two or more "-" like 1-5-10!

    If anyone can help me with JavaScript regex, thanks in advance!

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    /^\d+-\d+(,\d+-\d+)*$/
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Member
    Join Date
    Nov 2012
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    felgall thank you, this is the real solution!
    while I am here, may I ask you what I should change if I add plus any digit before or after... something like...

    ex1: 1,3-5,8-19,25,35,43
    ex2: 7,12-15,20,29,30-35,39-43
    or may be just digits like 4,8,11,17

  4. #4
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,068
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    That would be

    /^(\d+-\d+|\d+)(,(\d+|\d+-\d+))*$/

    This will for example also accept: 1,2,3,4,5-15,18

    Please note that this only checks on syntax, not correctness. i.e., 1-3,5-2,1,9-6 would be accepted just fine, while the range itself is completely weird (and can be rewritten to 1-9).
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Tags for this Thread

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
  •