【问题标题】:Remove inconsistent acronyms in strings using regex使用正则表达式删除字符串中不一致的首字母缩写词
【发布时间】:2021-05-03 15:46:11
【问题描述】:

我想删除所有首字母缩略词,即使是写得不一致的首字母缩写词。例如,在下面的列表 (text) 中,一些首字母缩略词缺少左括号或右括号,因此我也希望删除它们。我只能删除带有两个右括号的那些。

如何调整当前的 re 表达式,使其不仅仅关注带有 2 个括号的大写字符?

import re

text = ['Spain (ES)', 'Netherlands (NL .', 'United States (USA.', 'Russia RU)']  

for string in text:
  cleaned_acronyms = re.sub(r'\([A-Z]*\)', '', string) #remove uppercase chars with ( ). 
  print(cleaned_acronyms)

#current output
>>> Spain 
>>> Netherlands (NL .
>>> United States (USA.
>>> Russia RU)

期望的输出:

>>> Spain
>>> Netherlands
>>> United States
>>> Russia

【问题讨论】:

  • r'\([A-Z]*\)?'?
  • 在某种程度上有效,而不是 RU) 首字母缩略词。谢谢你的“?”小费!
  • 您可以将它们双向匹配直到字符串的末尾,并用空字符串替换 \s*(?:\([A-Z]{2,}\)?|[A-Z]{2,}\)).* regex101.com/r/jYWXji/1

标签: python regex string python-re


【解决方案1】:

您可以将括号之间的大写字符与任一侧匹配,然后是该行的其余部分。

\s*(?:\([A-Z]{2,}|[A-Z]{2,}\)).*

Regex demo

例如

import re

text = ['Spain (ES)', 'Netherlands (NL .', 'United States (USA.', 'Russia RU)']

for string in text:
    cleaned_acronyms = re.sub(r'\s*(?:\([A-Z]{2,}|[A-Z]{2,}\)).*', '', string)
    print(cleaned_acronyms)

输出

Spain
Netherlands
United States
Russia

【讨论】:

    【解决方案2】:

    你们可能相处得很好

     \(?\b[A-Z.]{2,3}\b.+
    

    a demo on regex101.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多