Home > Mobile >  Find a pattern in a string
Find a pattern in a string

Time:10-14

I have a string where I want to find a particular word in the string and then based on that select the substring. Example:

text = "1-zone[0B]"

In this text I would like to find the if 1-zone is present in the text then select the [0B] and then return [0B] in the form of a list.

I tried regex.search but I think it is not the right implementation.

CodePudding user response:

The following is one possible implementation, using re.search.

import re

text = "1-zone[0B, 1C]"

# for python 3.8 , the next two lines can be combined into:
# if m := re.search(r'1-zone.*\[(.*?)\]', text):

m = re.search(r'1-zone.*\[(.*?)\]', text)
if m:
    output = [x.strip() for x in m.group(1).split(',')]
else:  # in case text does not have 1-zone
    output = []

print(output) # ['0B', '1C']

CodePudding user response:

If your string only has one occurrence of the substring you need to find (1-zone in your example) - or you're only looking for the first occurrence of the substring you can try the following:

text = "1-zone[0B]"
text_to_find = "1-zone"
desired_text_idx = text.find(text_to_find)   len(text_to_find)
desired_text = text[desired_text_idx:]
# [0B]
  • Related