RegEx匹配两个或多个相同的字符非连续 [英] RegEx match two or more same character non-consecutive

查看:326
本文介绍了RegEx匹配两个或多个相同的字符非连续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得一个匹配任何包含两个或多个逗号的字符串的正则表达式?

我想这可以用一个应该匹配的内容和不应该的内容的示例来更好地解释

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.

推荐答案

这将匹配一个至少包含2个逗号的字符串(不是冒号) ):

This will match a string with at least 2 commas (not colons):

/,[^,] *,/

简单地说匹配逗号,后跟任意数量的非逗号字符,后跟另一个逗号。你也可以这样做:

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 few characters as possible rather than as many as possible. That's called a "reluctant" qualifier. (I hope regexps in your language of choice support them!)

有人建议 /,.*,/ 。这是一个非常糟糕的主意,因为它总是会遍历整个字符串,而不是停留在找到的前2个逗号中。如果字符串很大,那可能会很慢。

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.

这篇关于RegEx匹配两个或多个相同的字符非连续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆