Escape sequences
In an ordinary string literal a backslash is an ordinary character, which is
what you want for Windows paths and regular expressions. When you need a tab,
a line feed or a character you cannot type, put ! in front of the literal
and it reads escape sequences.
'' In an ordinary literal a backslash is just a backslash, and a
'' doubled quote stands for one quote character.
print "C:\tools\new [""quoted""]"
'' Put ! in front and the literal reads escape sequences instead.
print !"tab:[\t] quote:[\"] backslash:[\\]"
print !"two lines:\n this is the second"
'' Codes in hexadecimal or decimal, and Unicode code points.
print !"\x41\x42 \67 \&h44"
dim as ustring cafe = !"caf\u00E9"
print cafe; " is"; len( cafe ); " characters"
'' \U takes eight hex digits, for code points above U+FFFF.
dim as ustring face = !"\U0001F600"
print "U+1F600 is"; len( face ); " code units"
'' $ in front marks a literal that never reads escapes.
print $"raw: \t \n"
'' A program can build the characters as well as spell them.
print cbool( !"a\tb" = "a" & chr( 9 ) & "b" )
Output
C:\tools\new ["quoted"]
tab:[ ] quote:["] backslash:[\]
two lines:
this is the second
AB C D
café is 4 characters
U+1F600 is 2 code units
raw: \t \n
true
Without a prefix, the only special thing inside quotes is the quote itself:
write it twice, "", for one " in the text.
With !, a backslash starts an escape:
| Escape | Character |
|---|---|
\t | tab |
\n | line feed |
\r | carriage return |
\\ | a backslash |
\" | a quote |
\xHH, \&hHH | the character with that hexadecimal code |
\NNN | the character with that decimal code |
\uXXXX | the Unicode code point U+XXXX |
\UXXXXXXXX | any code point, including those above U+FFFF |
A $ prefix marks a literal that never reads escapes. It says the same as no
prefix at all, but states it, which is useful in code that also uses !
literals nearby.
\u and \U give you any Unicode character while the source itself stays
plain ASCII. A code point above U+FFFF, such as U+1F600, becomes two UTF-16
code units in a ustring, which Unicode explains.
The same escapes work in a block string opened with !""".
Activities
- Print a three-column table using
\tbetween the columns. - Spell the word "naive" with an i-diaeresis, written
\u00EF, print it and itslen.