0

I have a expression and I want to extract it in python 2.6. Here is the example:

[a]+[c]*0.6/[b]-([a]-[f]*0.9)

this going to:

(
  '[a]',
  '+',
  '[c]',
  '*',
  '0.6',
  '/',
  '[b]',
  '-',
  '(',
  '[a]',
  '-',
  '[f]',
  '*',
  '0.9',
  ')',
)

I need it a list. Please give me a hand. Thanks.

Susam Pal
  • 32,765
  • 12
  • 81
  • 103
Zeck
  • 6,433
  • 21
  • 71
  • 111

2 Answers2

1
>>> import re
>>> expr = '[a]+[c]*0.6/[b]-([a]-[f]*0.9)'
>>> re.findall('(?:\[.*?\])|(?:\d+\.*\d*)|.', expr)
['[a]', '+', '[c]', '*', '0.6', '/', '[b]', '-', '(', '[a]', '-', '[f]', '*', '0.9', ')']
Susam Pal
  • 32,765
  • 12
  • 81
  • 103
1

One approach would be to create a list of regular expressions to match each token, something like:

import re
tokens = [r'\[.?\]', r'\(', r'\)', r'\+', r'\*', r'\-', r'/', r'\d+?.\d+', r'\d+']
regex = re.compile('|'.join(tokens))

Then you could use findall on your expression to return a list of matches:

>>> regex.findall('[a]+[c]*0.6/[b]-([a]-[f]*0.9)')
<<< 
['[a]',
 '+',
 '[c]',
 '*',
 '0.6',
 '/',
 '[b]',
 '-',
 '(',
 '[a]',
 '-',
 '[f]',
 '*',
 '0.9',
 ')']
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108