Help me implement this regex: split by (newline or start of string) followed by digits…
- User
Help me implement this regex:
split by (newline or start of string) followed by digits followed by a dot
codedf['output'] = df['output'].apply(lambda s: re.split(r'', s, flags=re.MULTILINE)) - Assistant
You want a regular expression that splits a string in a pandas column whenever it encounters either:
The start of the string, or
A newline character, followed by digits and a dot, like "1.", "23.", etc.
✅ Correct Regular Expression pythonCopyEditr'(?m)(?<=^|\n)(?=\d+.)'
This uses:
(?m) or flags=re.MULTILINE to handle line starts properly.
(?<=^|\n) – positive lookbehind for start of string (^) or newline (\n).
(?=\d+.) – positive lookahead for one or more digits followed by a dot.
✅ Code Example pythonCopyEditimport pandas as pd import re
df = pd.DataFrame({ 'output': [ "1. First item\n2. Second item\n10. Tenth item", "1. Apple\n2. Banana\n3. Cherry" ] })
pattern = r'(?m)(?<=^|\n)(?=\d+.)'
df['output'] = df['output'].apply(lambda s: re.split(pattern, s)) print(df)
✅ Output Each string becomes a list split at the digit-dot points: bashCopyEdit[ ['1. First item', '2. Second item', '10. Tenth item'], ['1. Apple', '2. Banana', '3. Cherry'] ]
Let me know if you'd also like to remove leading/trailing whitespace from each split item.
- User
I got this error: Alternation alternatives need to have the same length inside lookbehind
- Assistant
Ah yes — great catch. That error happens because in Python's re module, lookbehinds ((?<=...)) must be fixed-width, but: pythonCopyEdit(?<=^|\n)
uses alternation (|) with different lengths:
^ is zero-width,
\n is one character wide.
This breaks the lookbehind rule in Python.
✅ Corrected Version (No Lookbehind) Instead of a lookbehind, use a non-consuming split with a lookahead only. This avoids the lookbehind altogether: pythonCopyEditr'(?=^|\n\d+.)'
This says:
Match a position where either:
It's the start of the string, OR
It's a newline, AND it's followed by digits and a dot (\d+.).
✅ Final Working Code pythonCopyEditimport pandas as pd import re
df = pd.DataFrame({ 'output': [ "1. First item\n2. Second item\n10. Tenth item", "1. Apple\n2. Banana\n3. Cherry" ] })
pattern = r'(?=^|\n\d+.)'
df['output'] = df['output'].apply(lambda s: re.split(pattern, s)) df['output'] = df['output'].apply(lambda lst: [item.strip() for item in lst if item.strip()]) # optional clean-up print(df)
✅ Output pythonCopyEdit[ ['1. First item', '2. Second item', '10. Tenth item'], ['1. Apple', '2. Banana', '3. Cherry'] ]