简体   繁体   中英

Regular Expression to match a string of numbers and dash in javascript

I need to match a string like 2431-72367 , ie, a string with at least one number before and after the dash and only one dash.

I need to check it in JavaScript. Can anyone give me the regex and explain it?

/^\\d+-\\d+$/ will work.

  • ^ signals the begin of the string.
  • \\d+ means one or more digits.
  • $ signals the end of the string.

As a result, /^\\d+-\\d+$/.test("2431-72367") returns true.

The regex could be something like this:

^\d+-\d+$

This means:

^             Start of string
    \d            Digit
    +             One or more
    -             "-"
    \d            Digit
    +             One or more
    $             End of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM