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.
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.
$ means "Match the end of the string" (the position after the last character in the string).
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.
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.
You can do this
/^[^-]+-[^-]+$/
^
depicts the start of the string
$
depicts the end of the string
[^-]+
matches 1 to many characters except -
/^[^-]*-[^-]*$/
Beginning of string, any number of non-hyphens, a hyphen, any number of non-hyphens, end of string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With