Skip to content
Advertisement

Product code looks like abcd2343, how to split by letters and numbers?

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

abcd2343 abw34324 abc3243-23A

So it is letters followed by numbers and other characters.

I want to split on the first occurrence of a number.

Advertisement

Answer

JavaScript

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

JavaScript

  • 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.

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


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:

JavaScript

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

JavaScript

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):

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement