Home > Software design >  How to split string by character length and not include next section of string?
How to split string by character length and not include next section of string?

Time:08-24

If I'm splitting a string by character length and wanted the split string to not include the next section of the string which is specified by a comma or by another wildcard. How do I do this whilst being below the character limit?

raw_string = ('ABCD,DEFG,HIJK')
split_string = re.findall(.{1,10}, raw_string)
> split_string = 'ABCD,DEFG,H'

How do I set my Regex so that my string produces something like this?

>split_string = "ABCD,DEFG"

CodePudding user response:

You might let it backtrack until it can assert a comma to the right.

Note that you are using re.findall that will return a list of matches.

import re

raw_string = 'ABCD,DEFG,HIJK'
split_string = re.findall(r".{1,10}(?=,)", raw_string)
print(split_string)

Output

['ABCD,DEFG']
  • Related