javascript 正则表达式匹配两个或多个不连续的相同字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9255840/
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
RegEx match two or more same character non-consecutive
提问by elclanrs
How can I get a regular expression that matches any string that has two or more commas?
I guess this is better explained with an example of what should match and what shouldn't
如何获得匹配任何具有两个或多个逗号的字符串的正则表达式?
我想这最好用一个应该匹配和不应该匹配的例子来解释
abcd,ef // Nop
abc,de,fg // Yup
// This is what I have so far, but it only matches consecutive commas
var patt = /\,{2,}/;
I'm not so good with regex and i couldn't find anything useful. Any help is appreciated.
我对正则表达式不太好,我找不到任何有用的东西。任何帮助表示赞赏。
回答by Alex D
This will match a string with at least 2 commas(not colons):
这将匹配一个至少包含 2 个逗号(不是冒号)的字符串:
/,[^,]*,/
/,[^,]*,/
That simply says "match a comma, followed by any number of non-comma characters, followed by another comma." You could also do this:
这只是说“匹配一个逗号,后跟任意数量的非逗号字符,然后是另一个逗号。” 你也可以这样做:
/,.*?,/
/,.*?,/
.*?
is like .*
, but it matches as fewcharacters as possible rather than as manyas possible. That's called a "reluctant" qualifier. (I hope regexps in your language of choice support them!)
.*?
就像.*
,但它匹配尽可能少的字符而不是尽可能多的字符。这就是所谓的“不情愿”限定词。(我希望您选择的语言中的正则表达式支持它们!)
Someone suggested /,.*,/
. That's a very poor idea, because it will always run over the entire string, rather than stopping at the first 2 commas found. if the string is huge, that could be very slow.
有人建议/,.*,/
。这是一个非常糟糕的主意,因为它总是会遍历整个字符串,而不是在找到的前 2 个逗号处停止。如果字符串很大,那可能会很慢。
回答by chameleon
if you want to get count of commas in a given string, just use /,/g , and get the match length
如果您想获取给定字符串中的逗号计数,只需使用 /,/g ,并获取匹配长度
'a,b,c'.match(/,/g); //[',',','] length equals 2<br/>
'a,b'.match(/,/g); //[','] length equals 1<br/>
'ab'.match(/,/g) //result is null