1

What's a pythonic way to parse this string in the brackets:

txt = 'foo[bar]'

to get as result:

bar

What have I tried:

How I would solve it and I believe it's not very elegant:

result = txt.split('[')[1].split(']')[0]

I strongly think there is a library or method out there that has a more fault-tolerant and elegant solution for this. That's why I created this question.

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
caliph
  • 1,389
  • 3
  • 27
  • 52
  • Possible duplicate of [Regular expression to return all characters between two special characters](https://stackoverflow.com/questions/9889635/regular-expression-to-return-all-characters-between-two-special-characters) – Georgy Jan 28 '19 at 09:47

3 Answers3

2

Using Regex.

Ex:

import re

txt = 'foo[bar]'
print(re.findall(r"\[(.*?)\]", txt))

Output:

['bar']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

One out of many ways, using slicing:

print(txt[4:].strip("[]"))

OR

import re

txt = 'foo[bar]'

m = re.search(r"\[([A-Za-z0-9_]+)\]", txt)
print(m.group(1))

OUTPUT:

bar
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

Another take on slicing, using str.index to find the locations of the starting and ending delimiters. Once you get a Python slice, you can just it just like an index into the list, except that the slice doesn't just give a single character, but the range of characters from the start to the end.

def make_slice(s, first, second):
    floc = s.index(first)
    sloc = s.index(second, floc)
    # return a Python slice that will extract the contents between the first
    # and second delimiters
    return slice(floc+1, sloc)

txt = 'foo[bar]'

slc = make_slice(txt, '[', ']')
print(txt[slc])

Prints:

bar
PaulMcG
  • 62,419
  • 16
  • 94
  • 130