-1

I am using re to split a string based on regular expression, but I would like to keep the delimiters in the output array.

To make it clear, for a set of delimiters and string input I want to split the input each time the delimiter is met, but instead of keeping all characters following and excluding the delimiter, I want all characters following and including the delimiter. For example if my input is "FFG1G2ZZ2", and my delimiters [F,G,Z], I want as an output: F F G1 G2 Z Z Z2

input_string = "FFG1G2ZZ2"
output_list = re.split("FGZ", input_string)

print(output_list)
out: ['','','1','2','','2']

print(desired_output)
out: ['F','F','G1','G2','Z','Z2']
ylnor
  • 4,531
  • 2
  • 22
  • 39
  • `out: ['','','1','2','','2']`, how did you mange to get this value if `FGZ` doesn't exist on the string? Why are you using `input`, a built-in function, as a variable name? As a python developer , your code makes me headaches. Voted close because your question needs more focus. – Pedro Lobito Mar 31 '21 at 21:00
  • Does this answer your question? [In Python, how do I split a string and keep the separators?](https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators) – Hamms Mar 31 '21 at 21:00
  • `re.findall(r'[A-Z]\d*', input)` –  Mar 31 '21 at 21:04
  • @Hamms : No, the question you refer too keep the separators as a separated element of the list, in my case the output would be ["F", "F", "G", "1", "G", "2", "Z", "Z", "2"], while what I want is to keep the delimiter within the spited element, ie ['F','F','G1','G2','Z','Z2'] – ylnor Mar 31 '21 at 21:06
  • @PedroLobito : I rename the input string to input_string, should be more clear now – ylnor Mar 31 '21 at 21:08

1 Answers1

2

Use findall:

re.findall(r'[FGZ][^FGZ]*', input_string)
Stuart
  • 9,597
  • 1
  • 21
  • 30