【问题标题】:Get all strings with same beginning and end and any number of the same letter in between获取具有相同开头和结尾的所有字符串以及其间任意数量的相同字母
【发布时间】:2018-04-19 17:57:30
【问题描述】:

我想在文本中搜索具有相同开头和结尾字母以及中间任意数量的相同字母的单词(也应该不区分大小写),例如lol、lool、Loool、loooooool 等都应该被捕获。

我想为这些词过滤 Pandas 数据框。
例如df[df.message.str.contains('lol', case=False)]

【问题讨论】:

  • 你想只用 pandas 做这个吗?
  • 是的,message 列是文本字符串。
  • 那么LL 呢?还是只是L(以相同的字母开头和结尾)?
  • “abracadabra”的匹配案例应该是什么?
  • 那么,什么代码不起作用? lol 肯定不会起作用。您尝试了哪些模式?

标签: python regex pandas


【解决方案1】:

使用反向引用,例如:

message_list = ['lol', 'look', 'looloo', 'lool', 'Loool', 'LaoL', 'loooooool']

import re

for word in message_list:
    m = re.match(r'^(.)(.)\2*\1$', word, re.IGNORECASE)
    if m:
        print(word, "matched")

给予:

lol matched
lool matched
Loool matched
loooooool matched

\1 匹配 第一个 括号组中的任何内容,\2 第二个,依此类推。

【讨论】:

  • . 将匹配任何字符,而不仅仅是字母。
  • @WiktorStribiżew:是的,但问题是“文本”,可以是任何东西。如果需要,可以使用包含数字和下划线的\w[A-Z]。这个问题有点含糊。
猜你喜欢
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 2018-10-29
  • 2016-02-19
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多