简体   繁体   English

正则表达式匹配javascript中的一串数字和破折号

[英]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.我需要匹配一个像2431-72367这样的字符串,即一个字符串,在破折号前后至少有一个数字,只有一个破折号。

I need to check it in JavaScript.我需要在 JavaScript 中检查它。 Can anyone give me the regex and explain it?谁能给我正则表达式并解释一下?

/^\\d+-\\d+$/ will work. /^\\d+-\\d+$/会起作用。

  • ^ signals the begin of the string. ^表示字符串的开始。
  • \\d+ means one or more digits. \\d+表示一位或多位数字。
  • $ signals the end of the string. $表示字符串的结束。

As a result, /^\\d+-\\d+$/.test("2431-72367") returns true.结果, /^\\d+-\\d+$/.test("2431-72367")返回真。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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