Python Forum
Regex Include and Exclude patterns in Same Expression - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Regex Include and Exclude patterns in Same Expression (/thread-40041.html)



Regex Include and Exclude patterns in Same Expression - starzar - May-23-2023

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



RE: Regex Include and Exclude patterns in Same Expression - buran - May-23-2023

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


RE: Regex Include and Exclude patterns in Same Expression - Gribouillis - May-23-2023

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