我想找出所有開始或結束或包含'的單詞、數字。
我嘗試撰寫如下 2 個正則運算式。如果是第二個,我補充?:說單詞末尾或單詞開頭的文本是可選的。但沒有得到所需的結果。你我做錯什么了嗎?我想找到I've, 'had, not', you're, 123'45- 基本上所有有 '
import re
xyz="I've never 'had somebody [redacted-number] [redacted-number] [redacted-number] not. not' you're 123'45"
print (re.findall("\w \'\w ", xyz))
print (re.findall("(?:\w )\'(?:\w )", xyz))
["I've", "you're", "123'45"]
["I've", "you're", "123'45"]
uj5u.com熱心網友回復:
您快到了。嘗試這個:
(?:\w )?'(?:\w )?
(?:\w )=>?:確保非捕獲組,\w 匹配 1 次到無限次之間的單詞字符。?確保在 0 到 1 次之間匹配前一個令牌。
https://regex101.com/r/N8Y9cQ/1
uj5u.com熱心網友回復:
您想捕獲所有包含其中任何位置的單詞,不是嗎?'嘗試這個:
re.findall("\w*'\w*", xyz)
uj5u.com熱心網友回復:
您可以使用
\w*(?!\B'\B)'\w*
\w '\w*|'\w
請參閱正則運算式演示 #1 /正則運算式演示 #2。
細節
\w*(?!\B'\B)'\w*- 零個或多個單詞字符,一個'字符(前面和后面沒有非單詞字符或字串的開頭/結尾),零個或多個單詞字符\w '\w*|'\w- 一個或多個單詞字符,'零個或多個單詞字符,或一個'字符,然后是一個或多個單詞字符。
請參閱Python 演示:
import re
xyz="I've never 'had somebody [redacted-number] [redacted-number] [redacted-number] not. not' you're 123'45"
print (re.findall(r"\w*(?!\B'\B)'\w*", xyz))
# => ["I've", "'had", "not'", "you're", "123'45"]
在 Pandas 中,您可以使用Series.str.findall:
df['result'] = df['source'].str.findall(r"\w*(?!\B'\B)'\w*")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481387.html
