[英]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:所以上面的字符串将返回true,但下面的两个将是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 -
[^-]+
匹配 1 到多个字符,除了-
/^[^-]*-[^-]*$/
字符串的开头、任意数量的非连字符、一个连字符、任意数量的非连字符、字符串的结尾。
奇怪(而不是 Regex )......但为什么不呢?
2 === str.split("-").length;
You could use a combination of indexOf
and lastIndexOf
:您可以结合使用
indexOf
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.