[英]If cell has 2 words, extract only 1st word and if cell has 3 words, extract 2 first words - PANDAS/REGEX
[英]Regex to extract ONLY alphanumeric words
我正在尋找一個正則表達式來提取僅包含字母數字字符的單詞:
string = 'This is a $dollar sign !!'
matches = re.findall(regex, string)
matches = ['This', 'is', 'sign']
這可以通過標記字符串並使用以下正則表達式分別評估每個標記來完成:
^[a-zA-Z0-9]+$
由於性能問題,我希望能夠在不標記整個字符串的情況下提取字母數字標記。 我最接近的是
regex = \b[a-zA-Z0-9]+\b
,但仍提取包含字母數字字符的子字符串:
string = 'This is a $dollar sign !!'
matches = re.findall(regex, string)
matches = ['This', 'is', 'dollar', 'sign']
是否有正則表達式能夠實現這一目標? 我嘗試了不同的方法,但無法提出解決方案。
除了單詞邊界之外,還可以向后和向前查找空格(或字符串的開頭/結尾):
(?:^|(?<= ))[a-zA-Z0-9]+(?= |$)
https://regex101.com/r/TZ7q1c/1
請注意,“ a”是一個獨立的字母數字單詞,因此也包含在內。
['This', 'is', 'a', 'sign']
無需為此使用正則表達式,python具有內置的isalnum
字符串方法。 見下文:
string = 'This is a $dollar sign !!'
matches = [word for word in string.split(' ') if word.isalnum()]
[感謝Khabz的評論進行編輯。 我誤解了這個問題]
根據您的意圖,您也可以“拆分”而不是“匹配”。
>>> matches = re.split(r'(?:\s*\S*[\$\!]+\S*\s*|\s+)', string)
['This', 'is', 'a', 'sign', '']
並且如果您需要刪除前導或結尾的空字符串:
>>> matches = [x for x in re.split(r'(?:\s*\S*[\$\!]+\S*\s*|\s+)', a) if x ]
['This', 'is', 'a', 'sign']
SomePerformance的使用前后觀察的響應是最緊湊的。 當指定了排除項時,使用split有時是有優勢的,即上面的正則表達式描述了需要排除的內容。 但是,在這種情況下,指定的是字母數字,因此使用split()不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.