我有一个字符串如下:
theatre = 'Regal Crown Center Stadium 14'
我想把它打成一个基于每个单词中第一个字母的首字母缩略词,但也包括两个数字:
期望的输出= 'RCCS14'
我的代码尝试如下:
acronym = "".join(word[0] for word in theatre.lower().split())
acronym = "".join(word[0].lower() for word in re.findall("(\w+)", theatre))
acronym = "".join(word[0].lower() for word in re.findall("(\w+ | \d{1,2})", theatre))
acronym = re.search(r"\b(\w+ | \d{1,2})", theatre)
在其中我结束了类似:rccs1
,但似乎无法捕获最后一个数字。可能存在这个数字位于名称中间的情况:'Regal Crown Center 14 Stadium'
。 TIA!
(?:(?<=\s)|^)(?:[a-z]|\d+)
(?:(?<=\s)|^)
确保前面的空格或行的开头(?:[a-z]|\d+)
匹配一个字母或一个或多个数字i
标志(python中的re.I
)允许[a-z]
匹配其大写变体。
import re
r = re.compile(r"(?:(?<=\s)|^)(?:[a-z]|\d+)", re.I)
s = 'Regal Crown Center Stadium 14'
print(''.join(r.findall(s)))
上面的代码查找正则表达式匹配的所有实例,并将列表项连接到单个字符串中。
结果:RCCS14
我不能评论,因为我没有足够的声誉,但S. Jovan的回答并不令人满意,因为它假设每个单词都以大写字母开头,并且每个单词都有一个且只有一个大写字母。
re.sub(r'[a-z ]+', '', "Regal Crown Center Stadium YB FIEUBFB DBUUFG FUEH 14")
将返回'RCCSYBFIEUBFBDBUUFGFUEH14'
但是,在这种情况下,ctwheels答案将能够起作用:
r = re.compile(r"\b(?:[a-z]|\d+)", re.I)
s = 'Regal Crown Center Stadium YB FIEUBFB DBUUFG FUEH 14'
print(''.join(r.findall(s)))
将打印
RCCSYFDF14
import re
theatre = 'Regal Crown Center Stadium 14'
r = re.findall("\s(\d+|\S)", ' '+theatre)
print(''.join(r))
给我RCCS14