search

Home  >  Q&A  >  body text

javascript - I always get an error when I write a regex to verify 12.5-20.5?

The required data format is:
1
10
100
1-5
10-50
100-500
0.5
10.5
10.5-20
10.5-20.5
10-20.5

That is, there is no limit to the size of the number required for verification. It can have floating point numbers or not, it can have "-" or not, and one decimal place is retained.

This is the regular expression I wrote:

The following copy is wrong:

var a=/^\d{1,}\.?\d?-?(\d{1,})?\.?\d?$/;

Corrected to:

var a=/^\d{1,}\.?\d{1}?-?(\d{1,})?\.?\d{1}?$/;

But why is 20.5555 always true?

typechotypecho2714 days ago940

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-06-26 10:59:35

    /^d{1,}.?d?-?(d{1,})?.?d?$/The matching process is as follows:
    First d{1,} matches "20";
    .? matches ".";
    d? matches "5", ? matches 1 time;
    -? matches "", because ? matches 0 or 1 times, match here 0 times;
    (d{1,})? matches "555", at this time ? matches 1 time;
    .?d? matches "", at this time both ? match 0 times ;
    $ matches the end of the string, so "20.5555" will match.

    Update1: The matching process of
    /^d{1,}.?d{1}?-?(d{1,})?.?d{1}?$/ is as follows:

    1. d{1,}matches "20";

    2. .?matches ".";

    3. d{1}? will first try to match a number, and then match "5", ?match 1 time;

    4. -? will match "", at this time ? matches 0 times;

    5. (d{1,})?matches "555";

    6. .? matches "", at this time ? matches 0 times;

    7. d{1}? matches "", ? matches 0 times;
      d{1} means that the number is repeated once, so the regular expression is actually the same as d, so the updated regular expression There is no difference between the expression and the original regular expression.

    Note: There was a problem with the matching process I wrote at the beginning, but it has been updated now.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:59:35

    const regex = /^\d+(?:\.\d)?(?:-\d+(?:\.\d)?)?$/;
    
    const cases = [
        "1",
        "10",
        "100",
        "1-5",
        "10-50",
        "100-500",
        "0.5",
        "10.5",
        "10.5-20",
        "10.5-20.5",
        "10-20.5",
        "20.5555",
        "20.5-20.5555"
    ];
    
    const r = cases.map(s => regex.test(s));
    console.log(r);

    reply
    0
  • 高洛峰

    高洛峰2017-06-26 10:59:35

    ???Why use regular expressions

    reply
    0
  • Cancelreply