[英]Regex - how to capture many words
我有一個簡單的正則表達式問題:
給定像"test-class"
這樣的字符串,我應該使用什么正則表達式來獲取['test','class']
(在python上下文中)
您不需要正則表達式; 只需使用str.split()
:
>>> 'test-class'.split('-')
['test', 'class']
正則表達式解決方案仍在拆分:
>>> import re
>>> re.split(r'-', 'test-class')
['test', 'class']
([a-zA-Z]*)
就足以捕獲字符串中的每個單詞。
如果您打算使用正則表達式:
簡而言之,您可以定義一個與所需內容匹配的正則表達式。 然后,對字符串使用regex.matchall
,然后取回匹配的部分。
import re
$ s = 'hello-world this 32'
$ results = re.findall(r'[a-zA-Z]*', s)
$ print(results)
['hello', '', 'world', '', 'this', '', '', '', '']
# Now we can filter out the empty results.
$ non_empty_results = [result for result in results if result]
$ print(non_empty_results)
['hello', 'world', 'this']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.