繁体   English   中英

Javascript Regex只匹配一次出现,不多也不少

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

我有一个像下面这样的字符串:

single-hyphen

我需要匹配连字符。 但是,我只想匹配一次出现的连字符,不多也不少。

所以上面的字符串将返回true,但下面的两个将是false:

1. a-double-hyphen
2. nohyphen

我如何定义一个正则表达式来做到这一点?

提前致谢。

你可以这样做

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

^描述字符串的开始

$表示字符串的结尾

[^-]+匹配 1 到多个字符,除了-

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

字符串的开头、任意数量的非连字符、一个连字符、任意数量的非连字符、字符串的结尾。

奇怪(而不是 Regex )......但为什么不呢?

2 === str.split("-").length;

您可以结合使用indexOflastIndexOf

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

http://jsfiddle.net/cSF8T/

非常规,但它有效。 它不操作字符串或使用正则表达式。

 // only true if only one occurrence of - exists in string
 (str.indexOf("-") + 1) % ( str.lastIndexOf("-") + 1 ) === 0

在这里摆弄

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM