Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Strings and Regular Expressions

Kotlin Strings and Regular Expressions

Strings are the most commonly used data type in programming, used to represent text.

Kotlin's String class provides rich methods for searching, substring extraction, and replacement, and also supports raw strings and string templates, making it much more concise than Java.

This article first introduces strings themselves, then covers the complete usage of the Regex regular expression class.


String basics and immutability

A string is wrapped in double quotes and has type String.

String is immutable: once created, its content cannot be changed.

All methods that look like "modifications", such as uppercase() and replace(), actually return a new string; the original stays unchanged.

Example

fun main

(

)

{

    val site

=

"Runoob"

   

// Calling uppercase gives a new string; the original is unaffected

    val upper

=

site.

uppercase

(

)

    println

(

site

)

       

// Runoob

    println

(

upper

)

       

// RUNOOB

   

// Use square brackets to get a character by index; indexing starts at 0

    println

(

site

[

0

]

)

     

// R

    println

(

site.

length

)

 

// 6

   

// Use a for loop to iterate over each character

   

for

(

c in site

)

{

        print

(

c

)

   

}

    println

(

)

           

// Output a newline

}



Runoob

RUNOOB

R

6

Runoob

To compare string contents, use ==which compares values;=== compares references; don't use it to test string equality.

Example

fun main

(

)

{

    val a

=

"runoob"

    val b

=

"runoob"

    val c

=

String

(

charArrayOf

(

'r'

,

'u'

,

'n'

,

'o'

,

'o'

,

'b'

)

)

    println

(

a

==

b

)

   

// true, contents are the same

    println

(

a

==

c

)

   

// true, contents are the same

    println

(

a

===

c

)

 

// false, c is an object created at runtime

}



true

true

false

Note:String immutability means concatenation and replacement create new objects. When repeatedly concatenating strings in a loop, use StringBuilder instead, otherwise many temporary objects will be created.


Escaped strings and raw strings

Kotlin has two string literals: escaped strings and raw strings.

An escaped string is wrapped in a pair of double quotes and supports escape sequences like \n and \t.

A raw string is wrapped in triple double quotes; content is preserved as-is, backslashes and quotes need no escaping, making it suitable for paths, JSON, and regex.

Example

fun main

(

)

{

   

// Escaped string: \n is interpreted as a newline

    val escaped

=

"First line\nSecond line"

    println

(

escaped

)

   

// Raw string: content is preserved as-is, including newlines

    val raw

=

""

"First line
Second line"

""

    println

(

raw

)

   

// In a raw string you can write backslashes directly, no escaping needed

    val path

=

""

"C:\Users\runoob\kotlin"

""

    println

(

path

)

   

// Especially convenient when writing JSON

    val json

=

""

"{"

site

": "

www.

runoob

.

com

"}"

""

    println

(

json

)

   

// In a raw string, $ is still the template start marker; to output a literal $ write ${'$'}

    val price

=

""

"${'$'}9.99"

""

    println

(

price

)

}



第一行

第二行

第一行

第二行

C:\Users\runoob\kotlin

{"site": "www.runoob.com"}

$9.99

Tip:The only character to watch out for in a raw string is $which still triggers string templating. To output a literal dollar sign, write ${'$'}。


trimIndent and trimMargin

When writing multiline text with a raw string, code indentation is preserved too, so there appear to be extra spaces.

trimIndent() removes the common indentation of all lines, as well as leading and trailing blank lines.

trimMargin() trims each line by a margin prefix (a vertical bar by default), suitable when you need to preserve some indentation.

Example

fun main

(

)

{

   

// trimIndent: remove common indentation

    val text

=

""

"
        Runoob
        www.runoob.com
        RUNOOB
    "

""

.

trimIndent

(

)

    println

(

text

)

   

// trimMargin: use | as the margin prefix by default

    val margin

=

""

"
        |Runoob
        |www.runoob.com
        |RUNOOB
    "

""

.

trimMargin

(

)

    println

(

margin

)

   

// You can also customize the margin prefix

    val custom

=

""

"
        >Runoob
        >RUNOOB
    "

""

.

trimMargin

(

">"

)

    println

(

custom

)

}



Runoob

www.runoob.com

RUNOOB

Runoob

www.runoob.com

RUNOOB

Runoob

RUNOOB

trimIndent() ignores blank lines when computing common indentation, so inserting blank lines in the middle doesn't affect the result.

trimMargin() only removes content before the margin prefix; the part after the prefix stays as-is, giving flexible control over each line's starting position.


String templates

String templates let you embed variables or expressions directly into a string, starting with $ at the beginning.

A simple variable name uses $namewhile an expression or a dotted call uses ${...}。

Example

fun main

(

)

{

    val siteName

=

"Runoob"

    val age

=

10

    println

(

"Site: $siteName"

)

                   

// Site: Runoob

    println

(

"$siteName has been online for $age years"

)

         

// Runoob has been online for 10 years

   

// Wrap complex expressions in curly braces

    println

(

"The length of $siteName is ${siteName.length}"

)

 

// The length of Runoob is 6

    println

(

"Next year is year ${age + 1}"

)

             

// Next year is year 11

   

// You can also call functions inside a template

    println

(

"Uppercase: ${siteName.uppercase()}"

)

       

// Uppercase: RUNOOB

   

// To output a literal $ you need to escape it

    println

(

"Price: $9.99"

)

                       

// Price: $9.99

}



站点:Runoob

Runoob 已上线 10 年

Runoob 长度是 6

明年是第 11 年

大写:RUNOOB

价格:$9.99

Note:When a variable name is immediately followed by other letters, you must use ${name} the form, otherwise the compiler will treat the following characters as part of the variable name. For example, "$siteNameSuffix" will look for a variable named siteNameSuffix.


// 2022-01-01 00:00:00 GMT

The table below lists the string methods most commonly used in everyday development.

Method Description Example
length Number of characters; a property, not a method "runoob".length gives 6
isEmpty() Whether it is an empty string "".isEmpty() gives true
isBlank() Whether it is blank (spaces count too) " ".isBlank() gives true
lowercase() Convert to lowercase, returning a new string "RUNOOB".lowercase() gives runoob
uppercase() Convert to uppercase, returning a new string "runoob".uppercase() gives RUNOOB
trim() Remove leading and trailing whitespace " Runoob ".trim() gives Runoob
split() Split by a delimiter into a List "a,b".split(",") gives [a, b]
replace() Replace all matches "a-b".replace("-", "+") gives a+b
substring() Extract a substring; the range is left-closed, right-open "runoob".substring(0, 3) gives run
padStart() Pad on the left with characters to a specified length "7".padStart(3, '0') gives 007
repeat() Repeat a specified number of times "ab".repeat(2) gives abab
startsWith() Whether it starts with a certain content "runoob".startsWith("run") gives true
contains() Whether it contains certain content, case-sensitive "runoob".contains("NO") gives false
indexOf() Return the index of the first occurrence, or -1 if not found "runoob".indexOf("o") gives 2
toInt() Parse into an integer; throws an exception on failure "42".toInt() gives 42

The examples below demonstrate the concrete results of these methods.

Example

fun main

(

)

{

    val s

=

"  Runoob Kotlin  "

    println

(

s.

length

)

                     

// 17

    println

(

s.

trim

(

)

)

                     

// Runoob Kotlin

    println

(

s.

trim

(

)

.

lowercase

(

)

)

         

// runoob kotlin

    println

(

s.

trim

(

)

.

uppercase

(

)

)

         

// RUNOOB KOTLIN

    println

(

s.

contains

(

"runoob"

)

)

         

// false, case-sensitive

    println

(

s.

trim

(

)

.

startsWith

(

"Run"

)

)

   

// true

    println

(

s.

trim

(

)

.

endsWith

(

"lin"

)

)

     

// true

    println

(

s.

trim

(

)

.

substring

(

0

,

6

)

)

     

// Runoob

    println

(

s.

trim

(

)

.

replace

(

"Kotlin"

,

"RUNOOB"

)

)

 

// Runoob RUNOOB

    println

(

s.

trim

(

)

.

indexOf

(

"Kotlin"

)

)

   

// 7

    println

(

"7"

.

padStart

(

3

,

'0'

)

)

         

// 007

    println

(

"ab"

.

repeat

(

3

)

)

               

// ababab

    println

(

"a,b,c"

.

split

(

","

)

)

           

// [a, b, c]

    println

(

""

.

isEmpty

(

)

)

                 

// true

    println

(

"   "

.

isBlank

(

)

)

               

// true

}



17

Runoob Kotlin

runoob kotlin

RUNOOB KOTLIN

false

true

true

Runoob

Runoob RUNOOB

7

007

ababab

[a, b, c]

true

true

split() can also take multiple delimiters at once, or accept a regular expression directly.

Example

fun main

(

)

{

   

// Multiple delimiters

    println

(

"a,b;c"

.

split

(

","

,

";"

)

)

         

// [a, b, c]

   

// Use a regex as the delimiter

    println

(

"a1b2c3"

.

split

(

Regex

(

""

"\d"

""

)

)

)

 

// [a, b, c]

   

// Limit the number of returned elements; the last element keeps the remaining content

    println

(

"a,b,c,d"

.

split

(

","

, limit

=

3

)

)

 

// [a, b, c,d]

}



[a, b, c]

[a, b, c]

[a, b, c,d]


String formatting

When you need alignment, zero-padding, or control over decimal places, you can use formatting functions.

On the JVM platform, Kotlin provides String.format() a static method and the string format() extension function, with syntax consistent with Java's format strings.

Example

fun main

(

)

{

    val name

=

"Runoob"

    val score

=

95.5

   

// String.format: placeholders correspond to the following arguments in order

    val s1

=

String

.

format

(

"%s scored %.2f"

, name, score

)

    println

(

s1

)

   

// The string format extension function is more compact

    val s2

=

"Site: %s, score: %d"

.

format

(

name,

96

)

    println

(

s2

)

   

// %-10s means left-aligned with width 10; %05d means pad with 0 on the left if fewer than 5 digits

    println

(

"%-10s|"

.

format

(

"runoob"

)

)

    println

(

"%05d"

.

format

(

42

)

)

   

// %x outputs hexadecimal

    println

(

"%x"

.

format

(

255

)

)

}



Runoob 的得分是 95.50

站点:Runoob,得分:96

runoob    |

00042

ff

The table below lists the most commonly used placeholders.

Placeholder Meaning Example result
%s String "%s".format("runoob") gives runoob
%d Decimal integer "%d".format(42) gives 42
%f Floating-point number, 6 decimal places by default "%f".format(3.14) gives 3.140000
%.2f Keep two decimal places "%.2f".format(3.14159) gives 3.14
%05d Width 5, pad with 0 if shorter "%05d".format(42) gives 00042
%-10s Width 10, left-aligned "%-10s|".format("runoob") gives runoob plus 4 spaces
%x Lowercase hexadecimal "%x".format(255) gives ff

Note:String.format Depends on the JVM; not available on Kotlin/JS or Kotlin/Native. For cross-platform code, use string templates or implement padding logic yourself.


Regular expressions: Regex

A regular expression describes a pattern of text and is commonly used for validation, extraction, and replacement.

Kotlin wraps regex functionality in the Regex class, created by calling the Regex constructor or the string's toRegex() extension function.

It's recommended to write regexes with raw strings so backslashes only need to be written once.

Example

fun main

(

)

{

   

// In a raw string, \d is the regex digit; no need to write \\d

    val regex

=

Regex

(

""

"\d+"

""

)

   

// matches: whether the entire string matches

    println

(

regex.

matches

(

"12345"

)

)

           

// true

    println

(

regex.

matches

(

"abc123"

)

)

           

// false

   

// containsMatchIn: whether there is any match

    println

(

regex.

containsMatchIn

(

"Order number abc123"

)

)

 

// true

   

// Equivalent form: use toRegex() to convert a string into a regex

    val same

=

""

"\d+"

""

.

toRegex

(

)

    println

(

same.

matches

(

"2026"

)

)

             

// true

}



true

false

true

true

find and findAll

find() returns the first match, while findAll() returns a sequence of all matches.

Example

fun main

(

)

{

    val regex

=

Regex

(

""

"\d+"

""

)

    val text

=

"Runoob September 8, 2026"

   

// find returns MatchResult?, which may be null

    val first

=

regex.

find

(

text

)

    println

(

first

?

.

value

)

                             

// 2026

    println

(

first

?

.

range

)

                             

// 7..10

   

// findAll returns a Sequenceand use map to extract the content

    val all

=

regex.

findAll

(

text

)

.

map

{

it.

value

}

.

toList

(

)

    println

(

all

)

                                     

// [2026, 9, 8]

   

// You can also take just the first two

    val firstTwo

=

regex.

findAll

(

text

)

.

take

(

2

)

.

map

{

it.

value

}

.

toList

(

)

    println

(

firstTwo

)

                                 

// [2026, 9]

}



2026

7..10

[2026, 9, 8]

[2026, 9]

A MatchResult's value is the matched text, and range is its index interval in the original string.

replace and split

replace() can replace all matches with specified content, and split() can split a string by matches.

Example

fun main

(

)

{

    val regex

=

Regex

(

""

"\d+"

""

)

   

// Replace all matches

    println

(

regex.

replace

(

"a1b2c3"

,

"#"

)

)

         

// a#b#c#

   

// Use a lambda to customize replacement content; it is the match result

    println

(

regex.

replace

(

"a1b2c3"

)

{

"<${it.value}>"

}

)

 

// a<1>b<2>c<3>

   

// Split by matches

    println

(

"a1b2c3"

.

split

(

regex

)

)

               

// [a, b, c]

   

// Replace only the first match

    println

(

regex.

replaceFirst

(

"a1b2"

,

"#"

)

)

     

// a#b2

}



a#b#c#

a<1>b<2>c<3>

[a, b, c]

a#b2

Capturing groups

Using parentheses you can group part of a regex into a capturing group, then extract each group's content separately after matching.

groupValues[0] is the whole match, followed by the 1st, 2nd, and 3rd capturing groups.

Example

fun main

(

)

{

   

// Three capturing groups: year, month, day

    val regex

=

Regex

(

""

"(\d{4})-(\d{2})-(\d{2})"

""

)

   

// matchEntire requires the entire string to match completely

    val match

=

regex.

matchEntire

(

"2026-09-08"

)

   

if

(

match

!=

null

)

{

        println

(

match.

groupValues

)

       

// [2026-09-08, 2026, 09, 08]

        println

(

match.

groupValues

[

1

]

)

   

// 2026

        println

(

match.

groupValues

[

2

]

)

   

// 09

        println

(

match.

groupValues

[

3

]

)

   

// 08

   

}

   

// Named capture group syntax: (?...)

    val named

=

Regex

(

""

"(? \d{4})-(?\d{2})"

""

)

    val m

=

named.

find

(

"Date: 2026-09"

)

!!

    println

(

m.

groups

[

"year"

]

?

.

value

)

     

// 2026

    println

(

m.

groups

[

"month"

]

?

.

value

)

   

// 09

}



[2026-09-08, 2026, 09, 08]

2026

09

08

2026

09

Both matchEntire() and matches() require the entire string to match; the difference is that the former returns MatchResult? while the latter returns only Boolean.

Regex options

When constructing a Regex you can pass a RegexOption to change matching behavior, such as ignoring case or multi-line mode.

Example

fun main

(

)

{

   

// IGNORE_CASE: ignore case

    val regex

=

Regex

(

"runoob"

, RegexOption.

IGNORE_CASE

)

    println

(

regex.

containsMatchIn

(

"Welcome to RUNOOB"

)

)

 

// true

    println

(

regex.

matches

(

"RUNOOB"

)

)

                   

// true

   

// Pass multiple options with setOf

    val multi

=

Regex

(

""

"^\d+"

""

, setOf

(

RegexOption.

MULTILINE

)

)

    val text

=

"123\n456"

    println

(

multi.

findAll

(

text

)

.

map

{

it.

value

}

.

toList

(

)

)

 

// [123, 456]

}



true

true

[123, 456]

Tip:If a regex needs to match characters .、*、+、?、( themselves, you must escape them with a backslash, or use Regex.escape() to turn a plain string into a safe regex fragment.


Common questions

Here are the most common issues when using strings and regexes.

Why the original value didn't change after modifying the string

Because String is immutable, all "modification" methods return new objects.

To save the result, you must use a variable to receive the return value, for example val s2 = s.replace("a", "b")。

How to output $ in a raw string

Raw strings don't support backslash escaping, so you need to write it as ${'$'}。

In an escaped string, write it directly as \$ .

Should string concatenation use + or a template

For a small amount of concatenation, string templates are the clearest and most readable.

For heavy concatenation in a loop you must use StringBuilder, otherwise every + creates a new string.

What's the difference between matches and find

matches() requires the entire string to match completely and returns Boolean.

find() returns a result as long as there is a match anywhere in the string, returning MatchResult?.

Why use triple quotes in regexes

Backslashes in a normal string need to be written twice, for example "\\d+"which is easy to get wrong.

Raw strings """\d+""" backslashes are written only once, closer to the regex's own notation.