繁体   English   中英

如何在 Python 中拆分字符串,直到某个特定字符从右到左出现?

[英]How to split a string in Python until one of specific characters occurs from right to left?

在Python中从右到左将字符串分成两部分直到出现几个字符之一的最佳方法是什么?

目的是将字符串分成两部分,最后带有版本号(以 A、B 或 C 开头),例如:

  • EP3293036A1 -> EP3293036 + A1
  • US10661612B2 -> US10661612 + B2
  • CN107962948A -> CN107962948 + A
  • ES15258411C1 -> ES15258411 + C1

我的代码适用于将字符串拆分为单个字符:

first_part = number.rpartition('A')[0]
second_part = number.rpartition('A')[1] + number.rpartition('A')[2]

有没有办法使用 rpartition 有多个参数,例如('A' or 'B' or 'C')? 或者有没有更好的方法使用正则表达式?

使用re.findall 使用显示的正则表达式,此函数提取括号中的部分: (.*?) - 任何重复 0 次或更多次的字符,非贪婪; ([AB]\d*)$ - A 或 B,后跟 0 个或多个数字,然后是字符串的结尾。

import re
lst = ['EP3293036A1', 'EP3293036B']

for s in lst:
    parts = re.findall(r'(.*?)([AB]\d*)$', s)
    print(f's={s}; parts={parts}')

# s=EP3293036A1; parts=[('EP3293036', 'A1')]
# s=EP3293036B; parts=[('EP3293036', 'B')]

您的示例数据表明您实际上想要在数字和其后的非数字之间进行拆分。 有了这个假设:

front, back = re.split(r'(?<=\d)(?=\D)', number)

尝试这个。

import re

def split_re(s):
    return [a for a in re.split(r'.{0}(?=[ABC])+',s) if a]  # Change `ABC` to `A-Za-z` if you want a partition if any alphabetic character is present likt('A','a','z','Y')
print(split_re('EP3293036A1'))  # -> ['EP3293036', 'A1']
print(split_re('US10661612B2')) # -> ['US10661612', 'B2']
print(split_re('CN107962948A')) # -> ['CN107962948','A']
print(split_re('ES15258411C1')) # -> ['ES15258411', 'C1']
print(split_re('CA107962948A')) # -> ['C', 'A107962948', 'A']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM