产品代码看起来像abcd2343,用字母和数字分割什么 [英] Product code looks like abcd2343, what to split by letters and numbers

查看:27
本文介绍了产品代码看起来像abcd2343,用字母和数字分割什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文本文件中有一个产品代码列表,每个类似的产品代码如下所示:

I have a list of product codes in a text file, on each like is the product code that looks like:

abcd2343 abw34324 abc3243-23A

abcd2343 abw34324 abc3243-23A

所以它是字母后接数字其他字符.

我想在第一次出现数字拆分.

推荐答案

In [32]: import re

In [33]: s='abcd2343 abw34324 abc3243-23A'

In [34]: re.split('(\d+)',s)
Out[34]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A']

或者,如果您想在第一次出现数字时进行拆分:

Or, if you want to split on the first occurrence of a digit:

In [43]: re.findall('\d*\D+',s)
Out[43]: ['abcd', '2343 abw', '34324 abc', '3243-', '23A']

<小时>

  • \d+ 匹配 1 个或多个数字.
  • \d*\D+ 匹配 0 个或多个数字后跟 1 个或多个非数字.
  • \d+|\D+ 匹配 1 个或多个数字 1 个或多个非数字.

    • \d+ matches 1-or-more digits.
    • \d*\D+ matches 0-or-more digits followed by 1-or-more non-digits.
    • \d+|\D+ matches 1-or-more digits or 1-or-more non-digits.
    • 请参阅文档,了解有关 Python 正则表达式的更多信息语法.

      Consult the docs for more about Python's regex syntax.

      re.split(pat, s) 将使用 pat 作为分隔符分割字符串 s.如果pat 以括号开头和结尾(从而成为捕获组"),则re.split 将返回pat 匹配的子串> 还有.例如,比较:

      re.split(pat, s) will split the string s using pat as the delimiter. If pat begins and ends with parentheses (so as to be a "capturing group"), then re.split will return the substrings matched by pat as well. For instance, compare:

      In [113]: re.split('\d+', s)
      Out[113]: ['abcd', ' abw', ' abc', '-', 'A']   # <-- just the non-matching parts
      
      In [114]: re.split('(\d+)', s)
      Out[114]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A']  # <-- both the non-matching parts and the captured groups
      

      相反,re.findall(pat, s) 只返回s 中与pat 匹配的部分:

      In contrast, re.findall(pat, s) returns only the parts of s that match pat:

      In [115]: re.findall('\d+', s)
      Out[115]: ['2343', '34324', '3243', '23']
      

      因此,如果 s 以数字结尾,则可以使用 re.findall('\d+|\D+', s) 避免以空字符串结尾而不是 re.split('(\d+)', s):

      Thus, if s ends with a digit, you could avoid ending with an empty string by using re.findall('\d+|\D+', s) instead of re.split('(\d+)', s):

      In [118]: s='abcd2343 abw34324 abc3243-23A 123'
      
      In [119]: re.split('(\d+)', s)
      Out[119]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A ', '123', '']
      
      In [120]: re.findall('\d+|\D+', s)
      Out[120]: ['abcd', '2343', ' abw', '34324', ' abc', '3243', '-', '23', 'A ', '123']
      

      这篇关于产品代码看起来像abcd2343,用字母和数字分割什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆