Link to home
Start Free TrialLog in
Avatar of Dennie
Dennie

asked on

python get location in string

Hi experts,

I need to find the location of the variable seperator  (,) in a php function call.

Some example function calls are shown below. The seperator locations are underlined.
test($var1, $var2, $var3);
test(array('hello, bye'), $bla);
test("string with 'quotes' \"quotes\" ",'ok',$bla);

How can I get the position of the seperator locations?
Avatar of pepr
pepr

What is the original intention?  Do you want to split the call by ',' (to get the separated tokens)?

I am not sure if there is any standard Python module/function to parse the arguments.  I usually write my own parser based on a finite automaton.  It may not be that short.  It is actually equivalent to a regular expression.  However--in my opinion--it is easier to modify the finite automaton than a complex regular expression.

If acceptable, I can show you how to write such a parser.  However, it may be a bit longer (not difficult, but the code is longer) than you expect.  Even though the result seems to be complicated, the parser will be quite fast when used.
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This code might be what you are looking for. However, it is not very flexible.
teststr = "test($var1, $var2, $var3);"
literal_list = ["'",'"']
delims = [',']
literal = ''

for index in range(len(teststr)):
	if literal == '':
		if teststr[index] in delims:
			print index
		elif teststr[index] in literal_list:
			literal = teststr[index]
	else:
		if teststr[index] == literal:
			literal = ''

Open in new window


If you want to look just at the variables rather than the entire call replace

teststr = "test($var1, $var2, $var3);"

Open in new window

with
teststr = "test($var1, $var2, $var3);".split('(',1)[1].rsplit(')',1)[0]

Open in new window


If none of the posts have what you need then you might want to explain a little more about the what and why.