簡體   English   中英

pandas python regex查找所有以'開頭、結尾或包含'的單詞

[英]pandas python regex find all words that begin, end or contain '

我想找出所有開始或結束或包含'的單詞、數字。

我嘗試編寫如下 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"]

您可以使用

\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*")

您想捕獲所有包含'單詞,不是嗎? 嘗試這個:

re.findall("\w*'\w*", xyz)

這將找到前面或后面有 0 個或多個單詞字符的任何'字符。 它匹配示例字符串中所有必需的單詞。 您的嘗試使用了 \w+ ,它需要在'之前和之后至少有一個單詞字符。 這就是為什么它不匹配'had and not'

在閱讀其他答案后,我會說 Wiktor 是最好的。 用那個。

您快到了。 嘗試這個:

(?:\w+)?'(?:\w+)?

(?:\w+) => ?:確保非捕獲組, \w+匹配單詞字符 1 到無限次。 ? 確保在 0 到 1 次之間匹配前一個令牌。

https://regex101.com/r/N8Y9cQ/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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