Ruby Ruby 正则问题

puma · July 03, 2017 · Last by puma replied at July 03, 2017 · 1251 hits

def duplicate_count(text)
  text.scan(/(\w)(?=(?!.*\1.*\1).*\1)/i).length                 
end

第二行怎么解释?

Count the number of Duplicates

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphanumeric characters, including digits, uppercase and lowercase alphabets.

Example

"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabbcdeB" -> 2 # 'a' and 'b'
"indivisibility" -> 1 # 'i'
"Indivisibilities" -> 2 # 'i' and 's'
"aa11" -> 2 # 'a' and '1'

为了找到重复的字符,很容易想到

(\w).*\1

但是如果某字符出现了 3 次 4 次怎么办?让它匹配最后两次重现就能保证不数重复了

(\w)(?!.*\1.*\1).*\1

我们在用这个正则 count 的时候,最后一个 \1 前面的 .* 包含了其他重现字符的话就会漏掉,那么改成 lookahead 就可以了

(\w)(?=(?!.*\1.*\1).*\1)
You need to Sign in before reply, if you don't have an account, please Sign up first.