Jay
Jay

Reputation: 15

regex split by multiple delimiter

I have a string:

inputString = "foo325434<453453 bar :"

I want to split the string by : < and whitespace while storing : <

So far I am doing the following:

inputArray = re.split(r'\s*(:|>|<)\s*', inputString)

The above code provides the following outcome:

['foo325434', '<', '453453 bar', ':', '']

I want the following outcome instead:

['foo325434', '<', '453453', 'bar', ':']

Upvotes: 1

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use

re.findall(r'[^:><\s]+|[:><]', inputString)

See the regex demo and the Python demo.

Details

  • [^:><\s]+ - 1+ chars other than :, <, > and whitespace
  • | - or
  • [:><] - a :, < or >.

re.findall will return all non-overlapping matches from a string.

Upvotes: 2

Related Questions