在第一个下划线之前返回所有字符

dur*_*dal 6 python regex string

re在Python中使用,我想返回字符串中第一次出现下划线之前的所有字符.另外,我希望返回的字符串全部为大写且没有任何非字母数字字符.

例如:

AG.av08_binloop_v6 = AGAV08
TL.av1_binloopv2   = TLAV1
Run Code Online (Sandbox Code Playgroud)

我很确定我知道如何使用大写字母返回一个字符串,string.upper()但我确信有几种方法可以.有效地删除它.任何帮助将不胜感激.我仍在缓慢但肯定地学习正则表达式.每个提示都会添加到我的笔记中以备将来使用.

为了进一步澄清,我上面的例子不是实际的字符串.实际的字符串看起来像:

AG.av08_binloop_v6
Run Code Online (Sandbox Code Playgroud)

我希望的输出看起来像:

AGAV08
Run Code Online (Sandbox Code Playgroud)

下一个例子也是一样的.串:

TL.av1_binloopv2
Run Code Online (Sandbox Code Playgroud)

期望的输出:

TLAV1
Run Code Online (Sandbox Code Playgroud)

再次感谢大家的帮助!

eum*_*iro 19

即使没有re:

text.split('_', 1)[0].replace('.', '').upper()
Run Code Online (Sandbox Code Playgroud)


Gum*_*mbo 7

试试这个:

re.sub("[^A-Z\d]", "", re.search("^[^_]*", str).group(0).upper())
Run Code Online (Sandbox Code Playgroud)

  • 实际上使用`re.compile`创建正则表达式对象会让你更清楚你写的东西,delnan(你只是用编译的字符串表达式代替字符串表达式).你实际上可以调用`a.sub("",b.search(s).group(0).upper())`. (2认同)