Files
30-seconds-of-code/snippets/words.md
Isabelle Viktoria Maciohsek 199b646c32 Fix tags
2020-10-25 12:43:20 +02:00

23 lines
592 B
Markdown

---
title: words
tags: string,regexp,beginner
---
Converts a given string into an array of words.
- 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(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']
```