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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13606905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:28:15  来源:igfitidea点击:

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

javascriptregex

提问by Obinwanne Hill

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.

提前致谢。

回答by Anirudha

You can do this

你可以这样做

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

^depicts the start of the string

^描述字符串的开始

$depicts the end of the string

$描述字符串的结尾

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

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

回答by Amadan

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

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

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

回答by jbabey

You could use a combination of indexOfand lastIndexOf:

你可以使用的组合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/

http://jsfiddle.net/cSF8T/

回答by VisioN

Weird (and not a Regex)... but why not?

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

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

回答by Bruno

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

在这里摆弄