Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex to match only a single occurrence no more or less

I have a string like below:

single-hyphen

I need to match the hyphen. However, I only want to match a single occurrence of the hyphen, no more or less.

So the string above will return true, but the two below will be false:

1. a-double-hyphen
2. nohyphen

How do I define a regex to do this?

Thanks in advance.

like image 929
ObiHill Avatar asked Nov 28 '12 14:11

ObiHill


People also ask

What is used for zero or more occurrences in regex?

You can repeat expressions with an asterisk or plus sign. A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.

What does '$' mean in regex?

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

What regular expression would you use to match a single character?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

What is \d in JavaScript regex?

The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Example 1: This example searches the non-digit characters in the whole string.


2 Answers

You can do this

/^[^-]+-[^-]+$/

^ depicts the start of the string

$ depicts the end of the string

[^-]+ matches 1 to many characters except -

like image 165
Anirudha Avatar answered Oct 12 '22 23:10

Anirudha


/^[^-]*-[^-]*$/

Beginning of string, any number of non-hyphens, a hyphen, any number of non-hyphens, end of string.

like image 36
Amadan Avatar answered Oct 12 '22 22:10

Amadan