0

My string is of the form my_str = "2a1^ath67e22^yz2p0". I would like to split based on the pattern '^(any characters) and get ["2a1", "67e22", "2p0"]. The pattern could also appear in the front or the back part of the string, such as ^abc27e4 or 27c2^abc. I tried re.split("(.*)\^[a-z]{1,100}(.*)", my_str) but it only splits one of those patterns. I am assuming here that the number of characters appearing after ^ will not be larger than 100.

1
  • I think your regex is just more complicated than it needs to be. r"\^[a-z]+ should be sufficient. Commented Aug 3, 2017 at 23:57

2 Answers 2

2

you don't need regex for simple string operations, you can use

my_list = my_str.split('^')

EDIT: sorry, I just saw that you don't want to split just on the ^ character but also on strings following. Therefore you will need regex.

my_list = re.split('\^[a-z]+', my_str)

If the pattern is at the front or the end of the string, this will create an empty list element. you can remove them with

my_list = list(filter(None, my_list))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Didn't know it was that easy haha
-1

if you want to use regex library, you can just split by '\^'

re.split('\^', my_str)

# output : ['2a1', 'ath67e22', 'yz2p0']

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.