compare

Compares two strings

Description

The fn:compare function returns one of the values:

-1 if $comparand1 is less than $comparand2

0 if $comparand1 is equal to $comparand2

1 if $comparand1 is greater than $comparand2

A comparand is greater than the other comparand if it starts with the other comparand and has additional characters. For example, abc is greater than ab.

Comparison operators (=, !=, <, <=, >, >=) can also be used to compare strings, and you may find the syntax more convenient. However, if you need to use a specific collation other than the default, you must use the fn:compare function.

Parameters

Description

comparand1:string()

the first string to compare

comparand2:string()

the second string to compare

collation:string()

the collation to use for sorting

Examples

These examples assume that no default collation is specified.

XPath

Results

Explanation

compare('a', 'b')

-1

'a' comes before 'b'.

compare('a', 'a')

0

The strings are equal.

compare('b', 'a')

1

'b' comes after 'a'.

compare('ab', 'abc')

-1

A string comes before a longer string that starts with it.

compare('a', 'B')

1

This shows that when using the simple code point collation, a lowercase a comes after an uppercase B.

compare(upper-case('a'), upper-case('B'))

-1

Converting both to upper case first makes the comparison ignore case.

compare('a', ())

()

If either argument is the empty sequence, the result is the empty sequence.

compare('Strasse', 'Straße', 'http://www.w3.org/2013/collation/UCA?lang=de;strength=primary')

0

The UCA collation for German, at primary strength, equates ß with ss.

compare('a', 'b', 'FOO')

Error FOCH0002

FOO is not a supported collation.

In a generator

Copy the snippet below and paste it in Freemapper, under a language node inside the generators element. Each line of the pattern prints the result of one example; to see them, run mi generate <project> <language> example-compare. The examples that raise an error are left out, because an error stops the generation.

[e] example-compare
    [e] start
        [e] match
            [v] /
        [e] body
            [e] write-pattern
                [v] examples
    [e] patterns
        [e] examples
            [v] E01: {{ compare('a', 'b') }}
            [v] E02: {{ compare('a', 'a') }}
            [v] E03: {{ compare('b', 'a') }}
            [v] E04: {{ compare('ab', 'abc') }}
            [v] E05: {{ compare('a', 'B') }}
            [v] E06: {{ compare(upper-case('a'), upper-case('B')) }}
            [v] E07: {{ compare('a', ()) }}
            [v] E08: {{ compare('Strasse', 'Straße', 'http://www.w3.org/2013/collation/UCA?lang=de;strength=primary') }}

See Also