1

I am trying to write a function (char-count) which takes a pattern and a string, then returns a number (count) which represents how many times any of the characters in the pattern appear in the string.

For example:

(char-count "Bb" "Best buy")

would return 2 since there is 1 match for B and 1 match for b, so added together we get 2

(char-count "AaR" "A Tale of Recursion")

would return 3 and so on


I tried using re-seq in my function, but it seems to work only for continuous strings. As in (re-seq #Bb "Best Buy) only looks for the pattern Bb, not for each individual character.

This is what my function looks like so far:

(defn char-count [pattern text]
  (count (re-seq (#(pattern)) text)))

But it does not do what I want. Can anybody help?

P.s. Very new to clojure (and functional programming in general).

Axoy
  • 13
  • 2

2 Answers2

6

You don't need anything nearly as powerful as a regular expression here, so just use the simple tools your programming language comes with: sets and functions. Build a set of the characters you want to find, and count how many characters from the input string are in the set.

(defn char-count [chars s]
  (count (filter (set chars) s)))
amalloy
  • 89,153
  • 8
  • 140
  • 205
1

Try wrapping the characters in [...] within the RegEx:

(count (re-seq #"[Bb]" "Best buy"))

Or, since you need that pattern to be dynamic:

(count (re-seq (re-pattern (str "[" pattern "]")) text))

But note that the solution might not work properly if the pattern contains special RegEx characters such as [, ], \, -, ^ - you'd have to escape them by prepending \\ in front of each one.

Eugene Pakhomov
  • 9,309
  • 3
  • 27
  • 53
  • `Pattern/quote` is the recommended way to quote patterns, not ad hoc code to put `\\` characters in front of stuff by hand. – amalloy Nov 01 '22 at 17:50
  • Depends on whom you ask, I suppose. `Pattern/quote` would work, but then you'd have to split the pattern into characters, escape every character, build a group for each, combine those groups with `|`. Whereas the set of metachars is well known. – Eugene Pakhomov Nov 02 '22 at 14:49