From 5a639e263b748ad9c7571c31cc3b661c08bdf872 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Mon, 5 Oct 2020 19:08:32 +0300 Subject: [PATCH] Update words.md Fixes #280 --- snippets/words.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/snippets/words.md b/snippets/words.md index e9034fff8..5cf782d22 100644 --- a/snippets/words.md +++ b/snippets/words.md @@ -5,18 +5,18 @@ tags: string,regexp,beginnner Converts a given string into an array of words. -- Use `re.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. -- Use `filter()` in combination with `None` to remove any empty strings. -- Omit the second argument to use the default regexp. +- Use `re.findall()` with the supplied `pattern` to find all matching substrings. +- Omit the second argument to use the default regexp, which matches alphanumeric and hyphens. ```py import re -def words(str, pattern = '[^a-zA-Z-]+'): - return list(filter(None, re.split(pattern, str))) +def words(s, pattern = '[a-zA-Z-]+'): + return re.findall(pattern, s) ``` ```py words('I love Python!!') # ['I', 'love', 'Python'] words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee'] +words('build -q --out one-item', r'\b[a-zA-Z-]+\b') # ['build', 'q', 'out', 'one-item'] ```