Page 1 of 1

Problem parsing square brackets in string literals

PostPosted: Sat Feb 23, 2008 8:11 am
by khjklujn
Cobra 0.7.3, Mono 1.2.6

The following program fails with "error: Expecting an expression" in line 3.
class Program
def main is shared
t = '0123['
print t.indexOf('[')

The workaround I am using is:
class Program
def main is shared
t as String = sharp' "0123[" '
print t.indexOf(sharp' "[" ')

Re: Problem parsing square brackets in string literals

PostPosted: Sat Feb 23, 2008 9:12 am
by Dafra
I've got the same problem each time there is a square bracket in a string. Maybe Cobra believes they are regexs ?
I use ns'123[' (no substitution) or r'123[' (raw). You should try both because I don't know the difference.

Re: Problem parsing square brackets in string literals

PostPosted: Sat Feb 23, 2008 11:32 am
by dennis
Rather than a regex, I think Cobra is probably looking for a variable substitution:

print 'Value: [foo]'


This works, for example:

a = '456'
b = '123[a]789'


I also tried escaping the bracket with a backslash or doubling the bracket. Neither worked.

t = '0123\[' # Nope
t = '0123[[' # Nope


So I think r'0123[' or ns'0123[' are the correct way.

This works, BTW (it gives '0123['):

s = '12'
t = '0[s]' + r'3['

Re: Problem parsing square brackets in string literals

PostPosted: Sat Feb 23, 2008 2:54 pm
by Charles
You are correct that square brackets are used for interpolation. Also, you can have any kind of expression. And you can use : followed by a .NET formatting code:
print '[person.lastName], [person.firstName]'
print '[amount:N2]'

If you search for "C# string formatting" or such you'll find info on the formatting codes.

ns stands for "no substitution". It still respects \n \r \t etc. as meaning newline, carriage return, tab etc.

r stands for "raw" which is like Python's r'aoeu' and C#'s @"aoeu". All characters are literal including backslashes and brackets. Most often used for regular expressions where backslashes are common.

I've wanted \[ to work for awhile, but just haven't gotten to it. I also see that a better error message could be given to guide people.