簡體   English   中英

正則表達式-如何捕獲許多單詞

[英]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']
"(\w+)"g

此處的示例: http : //regex101.com/r/mV9cE2

\\w將匹配所有字母數字字符的返回組

g修飾符:全局。 所有比賽(在第一個比賽中不返回)

([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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM