【问题标题】:Find a specific pattern in a string using regex [duplicate]使用正则表达式在字符串中查找特定模式 [重复]
【发布时间】:2018-08-08 14:23:51
【问题描述】:
RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." 

@pastorjnelson Pastor JN, I have spoken to you before.  But, lol, you didnt know who I was.  Or maybe, I didnt know2026 

假设我有两个如上所示的字符串。我想使用 Python 正则表达式从给定行 @____ 中获取特定的字符串模式。我怎样才能做到这一点? 第一个字符串的预期输出应该是@Complex,第二个字符串应该是@pastorjnelson。

【问题讨论】:

  • re.findall(r'@\S+', text)

标签: python json regex


【解决方案1】:
import re
s = """RT @Complex: 'Atlanta' Season 2 director: "If the first season is College Dropout, this one is Late Registration." 
@pastorjnelson Pastor JN, I have spoken to you before.  But, lol, you didnt know who I was.  Or maybe, I didnt know2026 
"""

print re.findall("@\w+", s)

输出:

['@Complex', '@pastorjnelson']

【讨论】:

  • 当我这样做时,它会给我像 [u'@Complex'] 和 [u'@pastorjnelson'] 作为回报。我只想要像@Complex这样的文字
  • sn-p 正在返回一个列表。您可以使用索引 0 访问所需的元素。例如: print re.findall("@\w+", s)[0]
  • 我有两个不同的字符串。所以我认为它不会在我的情况下返回列表。
【解决方案2】:

@.+?\W 匹配上述两个示例。

@ 是文字@

.+? 搜索任意序列的至少一个非换行符

\W 匹配非字母数字字符。

【讨论】:

  • IT 说 @.*+\W 的表达式无效
  • 啊,是的,你说的很对——这就是我在没有测试的情况下进行更改时发生的情况!现在应该修好了
猜你喜欢
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多