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 do this
/^[^-]+-[^-]+$/
^
depicts the start of the string
$
depicts the end of the string
[^-]+
matches 1 to many characters except -
/^[^-]*-[^-]*$/
字符串的开头、任意数量的非连字符、一个连字符、任意数量的非连字符、字符串的结尾。
奇怪(而不是 Regex )......但为什么不呢?
2 === str.split("-").length;
You could use a combination of indexOf
and lastIndexOf
:
String.prototype.hasOne = function (character) {
var first = this.indexOf(character);
var last = this.lastIndexOf(character);
return first !== -1 &&
first === last;
};
'single-hyphen'.hasOne('-'); // true
'a-double-hyphen'.hasOne('-'); // first !== last, false
'nohyphen'.hasOne('-'); // first === -1, false
Unconventional but it works. It doesn't manipulate the string or use regex.
// only true if only one occurrence of - exists in string
(str.indexOf("-") + 1) % ( str.lastIndexOf("-") + 1 ) === 0
Fiddle here
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.