0

I'm looking to convert a single string to a list of strings based upon a list of corresponding RegEx values.

My code currently looks like this:

def regexSplit(s, regexList):
    retList = [""]*len(regexList)

    i = 0
    for e in enumerate(regexList):
        retList[i] = regex.search(regexList[i], s)
        s = s.split(retList[i], 1)[1]

        i += 1

    return retList

When attempting to run the code, however, I am getting the error:

in regexSplit
    s = s.split(retList[i], 1)[1]
TypeError: expected a character buffer object

Goal Example:

I'm trying to get it so that passing values such that if

s = "|Y4000|,03/02/2015,2000,||,|REDLANDS|,|CA|,|92375|"

and

regexList = ['[\w\d]{5}', '[0,1][1-9][/][0-3][0-9][/][\d]{4}', '[-]?[\d]*', '[^|]{0,40}', '[\w\s]{0,30}', '[\w]{2}', '[\d]{0,5}']

the returned list would be:

["Y4000", "03/02/2015", "2000", "", "REDLANDS", "CA", "92375"]

Thanks in advance.

4
  • I think you might be better off replacing any split chars with a , and then just splitting on , It feels like that's more close to what you want to do. Commented Nov 22, 2015 at 19:41
  • The CSV-ish text file that I'm working with makes it difficult to use such reasonable approaches (some value fields contain , and " and other such complications...) Commented Nov 22, 2015 at 19:44
  • Yes, so we simply do a for loop over all replacements so for r in replacements: s.replace(r,',') that will replace all dividers with commas, then we split on the commas. Commented Nov 22, 2015 at 19:49
  • I think str.translate and split would be a lot simpler Commented Nov 22, 2015 at 21:12

1 Answer 1

2

For what you are trying to achieve, split is not the right function. Write one regex and create a subexpression for each of the strings you want to parse. Start with something like ([\w\d]{5}).*?([,][0,1][1-9][/][0-3][0-9][/][\d]{4}).*? ... and so forth.

Then you can use

p = re.compile('<your regex>')
m = p.match('ab')
retTuple = m.group(1,2,3,4,5,6)

and you can use the resulting Tuple just like a list (except that it is immutable).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.