regex - A simple regexp in python -
my program simple calculator, need parse te expression user types, input more user-friendly. know can regular expressions, i'm not familar enough this.
so need transform input this:
import re input_user = "23.40*1200*(12.00-0.01)*mm(h2o)/(8.314 *func(2*x+273.15,x))" re.some_stuff( ,input_user) # ???? in this:
"23.40*1200*(12.00-0.01)*mm('h2o')/(8.314 *func('2*x+273.15',x))" just adding these simple quotes inside parentheses. how can that?
update:
to more clear, want add simple quotes after every sequence of characters "mm(" , before ")" comes after it, , after every sequence of characters "func(" , before "," comes after it.
this sort of thing regexes can work, can potentially result in major problems unless consider input like. example, can whatever inside mm(...) contain parentheses of own? can first expression in func( contain comma? if answers both questions no, following work:
input_user2 = re.sub(r'mm\(([^\)]*)\)', r"mm('\1')", input_user) output = re.sub(r'func\(([^,]*),', r"func('\1',", input_user) however, not work if answer either question yes, , without cause problems depending upon sort of inputs expect receive. essentially, first re.sub here looks mm( ('mm('), followed number (including 0) of characters aren't close-parenthesis ('([^)]*)') stored group (caused parentheses), , close-parenthesis. replaces section string in second argument, \1 replaced first , group pattern. second re.sub works similarly, looking number of characters aren't comma.
if answer either question yes, regexps aren't appropriate parsing, language not regular. the answer question, while discussing different application, may give more insight matter.
Comments
Post a Comment