Erkennen Sie also diese DELIMITER:
Code: Select all
'A string with a DELIMITER to be used.'Code: Select all
"Another string. It\'s got a DELIMITER within escaped \' single-quotes."
Code: Select all
'A string with a "DELIMITER" inside quotes.'Code: Select all
'Another string with a \'DELIMITER\' inside quotes.'
Code: Select all
'A string with a " \"DELIMITER\" within escaped quotes within quotes", which should not be recognized.'
Code: Select all
>>> '"\"'
'""'
>>> len('"\"')
2
>>> '"\\"'
'"\\"'
>>> len('"\\"')
3
Code: Select all
from typing import List
def split_around_needles(expression: str, needles: List[str]) -> List[str]:
buffer: str = ''
parts: List[str] = []
open_quotes: str = ''
for char in expression:
buffer += char
if char in '"\'' and buffer[-1] != '\\':
# if the character is an unescaped quote (no \ before the ' or ")
if open_quotes == '':
# we are entering a quoted area
open_quotes = char
elif open_quotes == char:
# we are leaving the quoted area
open_quotes = ''
continue
if open_quotes != '' or (char not in needles.keys()):
# ignore every character inside valid quotes
# and every character that does not belong to a needle
continue
for needle in needles[char]:
if len(buffer) >= len(needle) and buffer[-1 * len(needle):] == needle:
# found a needle
buffer = buffer[0:-1 * len(needle)].strip()
if buffer != '':
parts.append(buffer)
buffer = ''
parts.append(needle)
if buffer != '':
parts.append(buffer)
return parts
# it does not matter at this point, but needles is a dictionary with the last
# character of the delimiter as its key:
# needles: List[str, str] = {}
# needles['+'] = '+'
# needles['R'] = 'DELIMITER'
# ....
Code: Select all
>>> split_around_needles('"abc" + de')
['"abc"', '+', ' de']
Code: Select all
>>> split_around_needles('"ab+c" + de')
['"ab+c"', '+', ' de']
Code: Select all
>>> split_around_needles('\"ab+c\" + de')
['"ab+c"', '+', ' de']
Code: Select all
>>> split_around_needles('"a\"b+c" + de')
['"a"b', '+', 'c" + de']
Code: Select all
>>> split_around_needles('a\\"+bc')
['a\\"+bc']
Kann mir jemand den richtigen Weg weisen?
Mobile version