Python Forum

Full Version: Regex Include and Exclude patterns in Same Expression
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How to split sep = "," at only ")," and exclude "%," ?

text = "METAL (3.25%,a/d=13/1),IT(2.31%,a/d=10/0),HEALTHCAREINDEX(1.32%,a/d=13/7)"
try1[No Work] > textSplit = text.split(r',') includes "%,"
try2[Works with issue]> textSplit = text.split(r'),') omits ")" at the end .How to add ")" back to the string.
try3[No Work]> textSplit = text.split(r'/(?<=[)],)/gm') positive lookahead doesn't split only at "),"

import re
import numpy as np

def randomColor(x):
    rColor = list(np.random.random(size=3) * 256) 
    return f'<span style = "color:rColor">{x}</span>'

def spanColor(text):
    textSplit =  text.split(r'/(?<=[)],)/gm')
    print(text)
    print(textSplit)
    textSplit_lst = [randomColor(x) for x in textSplit]
    textSplit_str = ",".join(textSplit_lst)

    return textSplit_str


def regex_func():
    print("Start")
    regStr = "METAL (3.25%,a/d=13/1),IT(2.31%,a/d=10/0),HEALTHCAREINDEX(1.32%,a/d=13/7)"
    regLst =  spanColor(regStr)
    print(f"regLst = {regLst}")


regex_func()
What is the **expected** result
>>> text_split = text.split('),')
>>> text_split
['METAL (3.25%,a/d=13/1', 'IT(2.31%,a/d=10/0', 'HEALTHCAREINDEX(1.32%,a/d=13/7)']
>>> text_split[:-1] = (f'{item})' for item in text_split[:-1])
>>> text_split
['METAL (3.25%,a/d=13/1)', 'IT(2.31%,a/d=10/0)', 'HEALTHCAREINDEX(1.32%,a/d=13/7)']
your try2 looks like working, just add the ) back
(May-23-2023, 02:38 AM)starzar Wrote: [ -> ]textSplit =  text.split(r'/(?<=[)],)/gm')
Where do you get this syntax from? Python is not Perl. The argument to str.split() is not a regex.