+ 1

Split a string with regex at the last occurrence of a space

I know that it could be done with regular rsplit(), but we are asked to use regex. import re txt = "Have you ever seen the rain" print(re.split("\s", txt,1)) #This is splitting at the first space and is giving: ['Have', 'you ever seen the rain'] # But how can i get the splitting done in this way always at the last occurrence of a space? ['Have you ever seen the', 'rain'] #Is there something like a rsplit() ? https://sololearn.com/compiler-playground/cWfJUqsa162C/?ref=app

11th Nov 2024, 7:29 PM
sandra
sandra - avatar
2 ответов
+ 3
Something like this? "\s+(?!\S*\s)" https://stackoverflow.com/a/41870151
11th Nov 2024, 7:41 PM
Lisa
Lisa - avatar
0
Lisa , Thank you so much, it is working. I am not very familiar with regular expressions, but I am afraid I have to delve deeper here.
11th Nov 2024, 8:01 PM
sandra
sandra - avatar