【问题标题】:Regex for negation of three @ followed by number and three @ at end正则表达式否定三个 @ 后跟数字和三个 @ 最后
【发布时间】:2017-05-30 20:59:53
【问题描述】:

我需要构建一个正则表达式,它以速率符号 @ 开头的三个取反,然后是 1 到 12 位之间不同长度的数字,并以三个 @ 符号结尾。应该选择除此之外的任何内容。

基本上我的挑战是我有一个数据框,它有一个文本语料库和一个模式@@@0-9@@@ 中的值我想删除除此模式之外的所有内容。我已经能够将正则表达式开发为[@][@][@]\d{1,12}[@][@][@],但是我想要否定这种模式,因为我想做查找和替换。例如

my name is x and i work at @@@12354@@@ and i am happy with my job. what is your company name? is it @@@42334@@@? you look happy as well!!

应该返回@@@12354@@@ @@@42334@@@,这样在各个元素之间有一个空格分隔符会很棒。有什么帮助吗?

我将在 python pandas 数据框 uisng str.replace 函数中使用这个正则表达式。

我已经尝试过regexr.comregex101.com 并且已经到此为止了

**编辑:**下面是数据

SNo details
1   account @@@0000082569@@@ / department stores uk & ie credit control operations
2   academic @@@0000060910@@@ , administrative, and @@@0000039198@@@ liaison coordinator
3   account executive, financial @@@0000060910@@@ , enterprise and partner group
4   2015-nasa summer internship- space power system @@@0000129849@@@ and testing
5   account technical @@@0000185187@@@ , technical presales, systems engineer
6   account @@@0000082569@@@ for car, van & 4x4 products in the east of england
7   account @@@0000082569@@@ for mikro segment and owners of the enterprises
8   account @@@0000082569@@@ - affinity digital display, mobile & publishing
9   account @@@0000082569@@@ @@@0000060905@@@ -energy and commodities @@@0000086889@@@ candidate
10  account @@@0000082569@@@ for companies department of external relevance

【问题讨论】:

  • 一个更简单的正则表达式是@{3}\d+@{3}
  • 您可以将.findallr'@{3}\d+@{3}' 一起使用,然后加入找到的匹配项。
  • 如果我用 [^@{3}\d+@{3}] 做否定,它不仅是对模式的否定,也是对模式之外的任何其他数字的否定

标签: python regex regex-negation


【解决方案1】:

这就是我在my comment 中的意思:

>>> df = pd.DataFrame({'col1':['at @@@12354@@@ and i am happy with my job. what is your company name? is it @@@42334@@@? you look happy as well!!', 'at @@@222@@@ and t @@@888888@@@?' ]})
>>> df['col1'].str.findall(r'@{3}\d+@{3}').apply(' '.join)
0    @@@12354@@@ @@@42334@@@
1     @@@222@@@ @@@888888@@@

@{3}\d+@{3} 将匹配用 3 个 @ 符号括起来的任何 1+ 数字,.findall 将提取所有匹配项。 .apply(' '.join) 将用空格连接值。

【讨论】:

  • 我收到 typeerror 'TypeError: can only join an iterable'
  • @Enthusiast:请发布您拥有的确切输入数据。您会看到我的示例包含数据初始化。它有效。
  • 我添加了示例数据
  • 但是它是如何初始化的呢?我的意思是,请以可复制的方式发布,例如df = pd.DataFrame({....})
  • 好吧,我调试了将近3个小时才意识到。在某些行中,它是一个 solli NaN 值。我将其替换为空格 '' 表示,您的代码是正确的。我接受这是有效的答案。谢谢!
【解决方案2】:

您可以将joinfindall 一起使用,而不是replace 与复杂的正则表达式,并像这样使用更简单的正则表达式:

>>> str = 'my name is x and i work at @@@12354@@@ and i am happy with my job. what is your company name? is it @@@42334@@@? you look happy as well!!'
>>> ' '.join(re.findall(r'@{3}\d{1,12}@{3}', str))
'@@@12354@@@ @@@42334@@@'

【讨论】:

    猜你喜欢
    • 2014-08-18
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多