javascript 正则表达式仅在字符串中的符号使用一次时才匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16762492/
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-10-27 05:53:37  来源:igfitidea点击:

Regex to match only if symbol in string used once

javascriptregex

提问by Kosmetika

Maybe it's a simple question but today i'm a bit stucked with it.

也许这是一个简单的问题,但今天我有点被它困住了。

I need regex to match only if symbol %appeared once in a string..

只有当符号%在字符串中出现一次时,我才需要正则表达式来匹配..

for example:

例如:

/regexpForSymbol(%)/.test('50%') => true
/regexpForSymbol(%)/.test('50%%') => false

Thanks!

谢谢!

回答by Jerry

You could use:

你可以使用:

^[^%]*%[^%]*$

The anchors are there to ensure every character is covered, and you probably already know what [^%]does.

锚点是为了确保每个角色都被覆盖,你可能已经知道是什么了[^%]

回答by melwil

Here you go. Don't expect everyone to make these for you all the time though.

干得好。不过,不要指望每个人都一直为你做这些。

^      # Start of string
[^%]*  # Any number of a character not matching `%`, including none.
%      # Matching exactly one `%`
[^%]*  # 
$      # End of string

回答by Niccolò Campolungo

You don't need regex.

你不需要正则表达式。

function checkIfOne(string, char) {
    return string.split(char).length === 2;
}

Usage:

用法:

var myString = "abcde%fgh",
    check = checkIfOne(myString, '%'); // will be true

回答by David Hellsing

You can use matchand count the resulting array:

您可以使用match和计算结果数组:

str.match(/%/g).length == 1