-1

I have the string "open this and close that" and I want to obtain "open this and" and "close that". This is my best attempt:

>>>print( re.split(r'[ ](?=(open|close)+)', "open this and close that") )
['open this and', 'close', 'close that']

I'm using Python 3.4.

Split string with multiple delimiters in Python replaces the triggers. I need them, the script has to know if I want to turn off or on a light, and not only which light is.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Welcome to SO! How about `re.split(r"(?<=and) (?=close)", s)`? It's not really clear what your logic is for this. Maybe more examples would help. – ggorlen Jan 15 '20 at 07:01
  • Maybe `re.findall(r"((?:open|close).*?)\s*(?=open|close|$)", s)` is closer to your intent? – ggorlen Jan 15 '20 at 07:11
  • I would use `output = [re.split('and')[0] + 'and', re.split('and')[1]]` – Will Jan 15 '20 at 07:28
  • 1
    Assuming that `this` and `that` are not static words, you just cannot do this in a reliable way. Your best bet would be to split on ` and ` (note the spaces around it) and add it back later. – ChatterOne Jan 15 '20 at 07:33
  • Does this answer your question? [Split string with multiple delimiters in Python](https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python) – Zsolt Botykai Jan 15 '20 at 07:55
  • Unrelated, update your Python version, it’s seriously outdated. – Konrad Rudolph Jan 15 '20 at 13:41
  • Thank you all and sorry, I'm new. I have a script for turning on and off the devices in my house. But, for each device I have to say "ok google, turn this on". I needed to be able to divide a sentence into several commands, for example if I leave the studio I say "ok google turn down the roller shutter of the studio, turn off the heating in the studio, turn off the studio light and turn on the light in the corridor". Now I can do it :D – Oscar Cappa Jan 16 '20 at 23:10

2 Answers2

1

You can simply use the grouping if you know what letter are you using.

import re
line = re.sub(r"(open this and) (close that)", r"\1\t\2", "open this and close that")
print (line)
pavithran G
  • 112
  • 2
  • 13
0

Assuming open and close are your keywords you could do :

import regex as re
print(re.search(r'(open.+)(close.+)', "open this and close that").groups())
('open this and ', 'close that')

Note that you don't erase the space character just before close

Clément
  • 1,128
  • 7
  • 21