0

I want to split a string on a character when it's in the middle of the string

Example :

string_1 = '-1232-1412'
string_2 = '1234-1243'

I want to have this :

output_string_1 = ['-1232','1412']
output_string_2 = ['1234','1243']

I tried this :

import re
In[1]: re.split(r'\w-',string_1)
Out[1]: ['-123', '1412']

but it deleted the last character before '-'

1

2 Answers 2

2

One way could be to split the string asserting not the start of the string ^ and after matching - asserting not the end of the string $ using a negative lookahead (?!

(?!^)-(?!$)

Regex demo | Python demo

Sign up to request clarification or add additional context in comments.

Comments

2

You may use this regex with word boundaries:

\b-\b

This regex matches hyphen wrapper with word boundaries on either side thus only matching hyphen in the middle of word characters.

Code:

>>> reg = r'\b-\b'
>>> print (re.split(reg, '-1232-1412'))
['-1232', '1412']
>>> print (re.split(reg, '1234-1243'))
['1234', '1243']

RegEx Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.