Count Words (Regex)

Count Words (Regex)

Write a function that counts words in a string using a regex — more robust than .split() for text with punctuation.

count_words_regex(s)

A "word" is a run of letters/digits/underscores (\w+). Punctuation like commas, periods, and hyphens should not count as part of a word, and should correctly separate words on either side of it.

Examples

count_words_regex("Hello, world!")     // → 2
count_words_regex("one-two three")      // → 3   ("one", "two", "three" -- the hyphen separates)
count_words_regex("  spaced   out  ")   // → 2

Walkthrough

Thinking it through

import re


def count_words_regex(s):
    return len(re.findall(r"\w+", s))

This is extract_digits's technique applied to a different character class: instead of \d+ (runs of digits), \w+ matches runs of "word characters" — letters, digits, and underscores. Anything that isn't a word character (spaces, commas, hyphens, periods) is automatically treated as a separator, since it simply can't be part of a \w+ match.

This is exactly why a regex handles "one-two three" more naturally than plain .split() would if you were trying to also strip punctuation: the hyphen in "one-two" isn't a word character, so \w+ finds "one" and "two" as two separate matches, without you needing to think about which punctuation marks to treat specially — \w+ already excludes all of them uniformly.

len(re.findall(...)) then just counts how many matches were found — same shape as extract_digits, just counting instead of joining.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.