简体   繁体   English

使用正则表达式在字符串中的任意位置多次查找字符

[英]Using regex to find a character a certain number of times anywhere in a string

I'm generating all possible permutations of a string 10 characters long with the numbers 1, 2, 3 . 我正在生成长度10个字符数字为1,2,3的字符串的所有可能排列。

I now want to check to see how many of the strings have the number 1 three times, 2 two times and 3 five times. 我现在要检查看看有多少个字符串的数字1是3倍, 2是2倍, 3是5倍。

What is the correct regex for this if I am using egrep? 如果我使用egrep,则正确的正则表达式是什么?

You can use positive lookaheads : 您可以使用正向前瞻

(?=(.*1){3})(?=(.*2){2})(?=(.*3){5})^.{10}$

See it in action 实际观看

However, note that this is not the perfect task to solve with regexes. 但是,请注意,这并不是用正则表达式解决的完美任务。


EDIT : Since you said you are using egrep , you can use piping instead: 编辑 :由于您说过您正在使用egrep ,因此可以使用管道代替:

echo 3121233133 | egrep '(.*1){3}' | egrep '(.*2){2}'| egrep '(.*3){5}' | egrep '^.{10}$'

This would be faster than regex: 这将比正则表达式更快:

input.replace("1", "").length === input.length - 3 &&
input.replace("2", "").length === input.length - 2 &&
input.replace("3", "").length === input.length - 5;

暂无
暂无

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

相关问题 正则表达式匹配包含特定字符多次的字符串 - Regex that matches a string that contains a specific character a certain number of times RegEx R:在字符串中的任意位置匹配具有相同字符确切次数的字符串 - RegEx R: match strings with same character exact number of times anywhere in string 正则表达式:在字符串末尾匹配一个在否定集中不匹配的字符仅一定次数 - Regex: Match a character that is unmatched in a negated set only a certain number of times at the end of a string 正则表达式:使用先行断言检查字符是否存在最多一定次数 - Regex: Using lookahead assertion to check if character exist at most a certain number of times 正则表达式不匹配:在任何地方搜索一定数量的数字 - Regex Mismatch: Searching anywhere for certain number of digits REGEX-在字符串中的任意位置匹配特殊字符 - REGEX - Match special character anywhere in the string 如果一个字符在字符串||的开头变为奇数次,则替换它 正则表达式 - Replacing if a character comes odd number of times in the begining of a String || Regex 正则表达式查找特定字符是否在String中存在奇数次 - Regex to find if a specific character exists odd times in String 正则表达式在字符串中查找任何字符使用次数超过3次但不连续 - Regex to find any character used more than 3 times in a string but not consecutively 使用正则表达式匹配特定字符是否出现特定次数 - Using Regex to match if a specific character occurs a specific number of times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM