Results 1 to 4 of 4

Thread: help with regular expression

  1. #1
    Join Date
    Sep 2011

    help with regular expression

    Hi, so I have this regular expression that is looking for a number.
    The text has an hour, and I want to extract the number.

    Its in the form: xxx hours (where x is the number).

    What I have:
    var pattern = /.*([0-9]{1,3})\W*h/i;
    var matches = pattern.exec (text);
    I want a number that can have from 1 to 3 digits, the problem is that 'matches' only gets a string with the number with one digit (the last digit), even if text has a number with more digits.

    If I change the part within the parentheses for {2}, it works well for 2 digits, etc.

    Is there a way to get the most digits, instead of just the least that conform with the pattern?

    So that if the text is "20 hours" I get "20".

    If its "3 hours" I get "3".

    (hope you understand what I mean )

  2. #2
    Join Date
    Feb 2006
    var text='Total of 20 hours';
    var pattern = /\d+(?= *hours)/i;
    var hours= pattern.exec (text);

  3. #3
    Join Date
    Sep 2011
    I tried that, but has two problems.

    First the number is not limited to three digits (although I guess I can deal with that later).
    If I have more than 1 space after the number, it gives null... but you do have the * there..

  4. #4
    Join Date
    Aug 2007
    var s = "Total of 2 hours";
    var r = /\d{1,3}(?=\s*hours)/;
    I'd go for something along those lines personally.
    Great wit and madness are near allied, and fine a line their bounds divide.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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

Recent Articles