Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for number and dash

Currently I write the regex like this: /^([\d+]*-)+([\d]*-)+([\d])*$/

I want the result follow this pattern 00-123-456-789 or 00123456789 (dash between number group or no dash at all)

  • not 00-123--457-789
  • or -00-123-456-789-
  • or -00123456789-
  • or 00-123-456-789-

How can I modify the regex to matches the pattern above?

like image 585
hungneox Avatar asked Nov 28 '11 08:11

hungneox


People also ask

How do you include a dash in regex?

The quantifier notations In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you write numbers in regular expressions?

Definition and Usage. The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

What is the difference between () and [] in regex?

6 Answers. Show activity on this post. [] denotes a character class. () denotes a capturing group.


1 Answers

Try something like this

/^(\d+-?)+\d+$/
like image 80
Phil Avatar answered Sep 28 '22 18:09

Phil