Monday, 19 September 2022

Quick guide to strings in TOML

String is a collection of characters. You can express a string in 4 ways.

 

a.   Basic Strings

b.   Multi line strings

c.    Literal strings

d.   Multi-line literal strings

 

All the strings must contain valid UTF-8 characters.

 

Basic Strings

Strings are defined in between double quotes. Any Unicode character may be escaped with the \uXXXX or \UXXXXXXXX forms.

 

basicStrings.toml

str1 = "Hello World"
str2 = "你好世界"

Multi line basic strings

Multi line basic strings are used to express passages of text. Multi line strings are defined between three double quotes. A newline immediately following the opening delimiter will be trimmed.

str1 = """
I am Krishna
and
I am from India"""

Above snippet is equivalent to following json.

{
  "str1": "I am Krishna\nand\nI am from India"
}

For writing long strings without introducing extraneous whitespace like \n, use a "line ending backslash". When a line ends with \, it will be trimmed along with all whitespace (including newlines) up to the next non-whitespace character or closing delimiter.

str2 = """
I am Krishna \



and \
I am from India"""

Above snippet is equivalent to following json.

{
  "str2": "I am Krishna and I am from India"
}

You can use single, double quotation marks inside a multiline strings.

str3 = """
This is Krishna's book \
and the book name is "Self learning Java"."""

Above snippet is equivalent to following json.

{
  "str3": "This is Krishna's book and the book name is \"Self learning Java\"."
}

multiLineBasicStrings.toml

str1 = """
I am Krishna
and
I am from India"""

str2 = """
I am Krishna \



and \
I am from India"""

str3 = """
This is Krishna's book \
and the book name is "Self learning Java"."""

Literal Strings

Literal strings are defined in between single quotes. Like basic strings, these also must appear in a single line. Literal strings do not allow escaping.

Whatever you write in single quotes, you will get exactly the same string, no escaping.

 

literalStrings.toml

path1  = 'C:\Users\krishna\Documents'
path2 = '\\Users\krishna$\\\t\'
quotedStr   = 'Book name is "self learning Java"'
regexEx    = '<\c\i*\d*>'

As literal strings do not support escaping, there is no way you can write a single quote in the literal string. You can use Multi-line literal strings to address this problem.

 


Multi-line literal strings

Multi-line literal strings are surrounded by three single quotes. Just like literal strings, it do not support escaping.

 

multiLineLiteralStrings.toml

str1 = '''
I am Krishna
and
I am from India'''

Since Multi-line literal strings do not allow escaping, you can insert 1 or 2 single quotes anywhere within a multi-line literal string, but not a sequence of 3 or more single quotes permitted.

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment