简体   繁体   中英

How to fetch whole string from start of comma to next comma or newline when “/” occurs in string

I have string in format

,xys=2/3,
d=e,
b*y,
b/e

I want to fetch xys=2/3 and b/e .

Right now I have regular expression which just picks 2/3 and b/e .

 pattern = r'(\S+)\s*(?<![;|<|#])/\s*(\S+)'
 regex = re.compile(pattern,re.DOTALL)
 for result in regex.findall(data):
     f.write("Division   " + str(result)+ "\n\n\n") 

How can I modify to pick what I intend to do?

  • Match anything but , (or newlines) up until the first slash / : [^,/\\n]*/
  • Match the remaining text up to the next comma: [^,\\n]*
  • Put the two together: [^,/\\n]*/[^,\\n]*

No need for regular expressions.

s = """,xys=2/3,
d=e,
b*y,
b/e
"""
l = s.split("\n")

for line in l:
    if '/' in line:
        print(line.strip(","))

Will this work:

x.split(",")[1].split('\n')[0] if "," in x[:-1] else None

It ignores (evaluates to None) unles , is present in the non-last position, else extract the part between , and another , or till the end, and again filter until new line if any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM