简体   繁体   English

您可以在javascript中使用RegEx来查看字符串是否包含一定数量的某些字符吗?

[英]Can you use a RegEx in javascript to see if a string contains a certain number of certain characters?

Say I am given a string (555)-555-5555, is there a way to check if the string contains exactly 10 occurrences of the number 5? 假设我得到了一个字符串(555)-555-5555,是否可以检查该字符串是否恰好包含10个数字5? I can think of other ways to solve this, but I am curious if this can be done with a regEx. 我可以想到其他方法来解决此问题,但我很好奇是否可以使用regEx来完成。 I tried using var re = new regExp(/5{10}/); 我尝试使用var re = new regExp(/5{10}/); but apparently this only matches ten 5's in a row. 但这显然只能连续匹配十个5。

1) Delete all non- 5 , count the remains. 1)删除所有非5 ,计数剩余的。

str.replace(/[^5]/g, '').length == 10

2) Count 5 -with-a-tail groups: 2)数5尾组:

str.match(/^[^5]*(?:5[^5]*){10}$/)

EDIT: fixed bugs. 编辑:修复错误。 Also, the explanation: the entirety of the string ( ^...$ ) consists of any number of non- 5 , followed by exactly 10 groups of one 5 and any number of non- 5 . 另外,还要说明一下:字符串( ^...$ )的整体由任意数量的非5 ,紧随其后的是10个一组,分别为1 5和任意数量的non- 5 Thus, 从而,

x55pp5peep5o5555taco5lol5

breaks down into 分解为

^               start of string
[^5]*           x
(?:5[^5]*){10}  5
                5pp
                5peep
                5o
                5
                5
                5
                5taco
                5lol
                5
$               end of string

A "mostly" regex solution would be to match replace all other characters with the empty string and check the length of your result. 一个“主要”的正则表达式解决方案是用空字符串匹配替换所有其他字符,并检查结果的长度。 Or similarly you could match and replace the character you want with the empty string and take the difference and see if it's the number you want. 或者类似地,您可以将所需的字符匹配并替换为空字符串,然后取其差值,看是否是您想要的数字。

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

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