[英]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}$
However, note that this is not the perfect task to solve with regexes. 但是,请注意,这并不是用正则表达式解决的完美任务。
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.