ZetCode

Perl regex Unicode properties

last modified November 25, 2026 Perl 5.44

Perl regular expressions work on Unicode text. Every character has properties in the Unicode database, such as its category, its script and its case, and a pattern can match by these properties instead of by listing characters. This article shows the properties that are most useful for text processing, and how to work with characters that consist of several code points.

All examples contain non-ASCII text in the source. The use utf8 pragma tells Perl that the source is UTF-8, so the string literals are decoded into characters. The binmode call encodes the output back to UTF-8. Patterns must always work on decoded character strings, as explained in Perl UTF-8 and encoding.

Word characters beyond ASCII

A character range such as [A-Za-z] covers only the 52 letters of the English alphabet. The \w class, on the other hand, follows Unicode and matches letters of every language.

word_chars.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $text = 'Zoë drinks čaj in a café';

my @ascii = $text =~ /[A-Za-z]+/g;
say "[A-Za-z]+: ", join '|', @ascii;

my @words = $text =~ /\w+/g;
say "\\w+:       ", join '|', @words;

The ASCII range breaks the words with accented letters into pieces and drops the accented letters. \w keeps every word whole. The /a modifier would restrict \w to ASCII again, see Perl regex modifiers.

$ perl word_chars.pl
[A-Za-z]+: Zo|drinks|aj|in|a|caf
\w+:       Zoë|drinks|čaj|in|a|café

Letters with \p{L}

The escape \p{...} matches a character that has the given property, and \P{...} matches a character that does not have it. The property L stands for letters. Unlike \w, it does not include digits and the underscore.

letters.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $text = 'room_42: Ünal, Zoë & 王';

my @letters = $text =~ /\p{L}+/g;
say "\\p{L}+: ", join '|', @letters;

my @words = $text =~ /\w+/g;
say "\\w+:    ", join '|', @words;

my @other = $text =~ /\P{L}+/g;
say "\\P{L}+: ", join '|', @other;

\p{L}+ finds the runs of letters in Latin and in Chinese. \w+ also accepts the digits and the underscore of the room name. The negated \P{L}+ returns everything between the letters: digits, punctuation and spaces.

$ perl letters.pl
\p{L}+: room|Ünal|Zoë|王
\w+:    room_42|Ünal|Zoë|王
\P{L}+: _42: |, | & 

General categories

Every character belongs to one general category. The categories have one-letter groups, such as L for letters, N for numbers, P for punctuation and S for symbols. Each group has two-letter subcategories, for example Lu for upper case letters or Sc for currency symbols.

categories.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $text = 'Émile paid 25 € and ½ of £8; Ünal said «thanks»!';

say "Lu (upper case):   ", join ' ', $text =~ /\p{Lu}/g;
say "Ll (lower case):   ", join ' ', $text =~ /\p{Ll}+/g;
say "N  (numbers):      ", join ' ', $text =~ /\p{N}+/g;
say "Nd (digits):       ", join ' ', $text =~ /\p{Nd}+/g;
say "Sc (currency):     ", join ' ', $text =~ /\p{Sc}/g;
say "P  (punctuation):  ", join ' ', $text =~ /\p{P}/g;

The difference between N and Nd is worth noting. The fraction ½ is a number, but not a decimal digit. The Sc category finds both currency signs, and P finds the guillemets along with ordinary punctuation. The full list of properties is in the perluniprops documentation.

$ perl categories.pl
Lu (upper case):   É Ü
Ll (lower case):   mile paid and of nal said thanks
N  (numbers):      25 ½ 8
Nd (digits):       25 8
Sc (currency):     € £
P  (punctuation):  ; « » !

Scripts

Properties also exist for writing systems, called scripts in Unicode. Examples are \p{Latin}, \p{Cyrillic}, \p{Greek}, \p{Han}, \p{Hiragana} and \p{Hebrew}.

scripts.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my @words = ('dobrý', 'привет', 'γειά', '你好', 'こんにちは', 'שלום', '42');

for my $word (@words) {
    my $script = $word =~ /^\p{Latin}+$/    ? 'Latin'
               : $word =~ /^\p{Cyrillic}+$/ ? 'Cyrillic'
               : $word =~ /^\p{Greek}+$/    ? 'Greek'
               : $word =~ /^\p{Han}+$/      ? 'Han'
               : $word =~ /^\p{Hiragana}+$/ ? 'Hiragana'
               : $word =~ /^\p{Hebrew}+$/   ? 'Hebrew'
               :                              'other';

    say "$word: $script";
}

Each word is tested against a chain of anchored patterns, and the first script that covers the whole word is reported. The Slovak word with an accented letter is still Latin. Digits do not belong to any of the listed scripts, they are shared by all of them.

$ perl scripts.pl
dobrý: Latin
привет: Cyrillic
γειά: Greek
你好: Han
こんにちは: Hiragana
שלום: Hebrew
42: other

Detecting mixed scripts

Some letters in different scripts look the same. The Cyrillic а is indistinguishable from the Latin a, and the Greek ο from the Latin o. Attackers use such look-alikes in domain names and user names. Script properties detect them.

mixed.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my @names = ('paypal', "p\x{430}ypal", 'перл', 'όπερα', "\x{3bf}pera");

for my $name (@names) {
    my $latin    = $name =~ /\p{Latin}/;
    my $cyrillic = $name =~ /\p{Cyrillic}/;
    my $greek    = $name =~ /\p{Greek}/;

    my $count = ($latin ? 1 : 0) + ($cyrillic ? 1 : 0) + ($greek ? 1 : 0);
    my $verdict = $count > 1 ? 'SUSPICIOUS, mixed scripts' : 'ok';

    printf "%-8s %s\n", $name, $verdict;
}

The second and the last name look like ordinary Latin words, but each contains one foreign letter, written with a \x{...} escape. A name that contains letters from more than one of the scripts is reported as suspicious. Names written completely in Cyrillic or Greek are fine.

$ perl mixed.pl
paypal   ok
pаypal   SUSPICIOUS, mixed scripts
перл     ok
όπερα    ok
οpera    SUSPICIOUS, mixed scripts

Grapheme clusters with \X

What a reader sees as one character can consist of several code points. The letter é can be stored as one code point, or as e followed by a combining accent. A flag consists of two regional indicator symbols. The \X escape matches one such user-perceived character, called an extended grapheme cluster. The \p{M} property matches combining marks.

graphemes.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $composed   = "caf\x{e9}";
my $decomposed = "cafe\x{301}";
my $flag       = "\x{1F1F8}\x{1F1F0}";

for my $s ($composed, $decomposed, $flag) {
    my $points = length $s;
    my $chars  = () = $s =~ /\X/g;
    my $marks  = () = $s =~ /\p{M}/g;

    say "$s: code points $points, graphemes $chars, marks $marks";
}

say "equal strings: ", $composed eq $decomposed ? 'yes' : 'no';

The two spellings of café look identical, but the second has an extra code point, the combining acute accent. length counts code points, while counting \X matches gives the four visible characters in both cases. The flag of Slovakia is two code points and one grapheme. The two spellings are not equal as strings. The Unicode::Normalize module converts them to a common form.

$ perl graphemes.pl
café: code points 4, graphemes 4, marks 0
café: code points 5, graphemes 4, marks 1
🇸🇰: code points 2, graphemes 1, marks 0
equal strings: no

Shortening text safely

The difference between code points and graphemes matters when text is cut, for example to fit a title into a fixed width. Cutting by code points can separate a letter from its accent.

truncate.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

sub shorten {
    my ($text, $max) = @_;

    my @chars = $text =~ /\X/g;
    return $text if @chars <= $max;

    return join('', @chars[0 .. $max - 2]) . '…';
}

my $title = "Cre\x{300}me bru\x{302}le\x{301}e recipe";

say "substr:  ", substr($title, 0, 3) . '…';
say "shorten: ", shorten($title, 4);
say "shorten: ", shorten($title, 10);
say "shorten: ", shorten('Tea', 4);

The title uses decomposed letters. substr cuts after three code points, which separates the e from its grave accent, so the accent disappears. The shorten function splits the text into graphemes with /\X/g and keeps whole characters, leaving room for the ellipsis. Text that is short enough is returned unchanged.

$ perl truncate.pl
substr:  Cre…
shorten: Crè…
shorten: Crème brû…
shorten: Tea

Case-insensitive matching

For Unicode strings, the /i modifier uses full case folding. It handles accented letters and also cases in which one character folds to several, such as the German ß, which folds to ss.

folding.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my @words = ('Straße', 'STRASSE', 'strasse', 'ŠKODA', 'škoda');

for my $word (@words) {
    my $street = $word =~ /^strasse$/i ? 'yes' : 'no';
    my $brand  = $word =~ /^škoda$/i   ? 'yes' : 'no';

    printf "%-8s strasse: %-3s škoda: %s\n", $word, $street, $brand;
}

The pattern strasse matches all three spellings of the German word, including the one with ß. The pattern with the Slovak š matches the brand name in both cases. For comparing strings outside of regular expressions, Perl has the fc function, see Perl fc.

$ perl folding.pl
Straße   strasse: yes škoda: no
STRASSE  strasse: yes škoda: no
strasse  strasse: yes škoda: no
ŠKODA    strasse: no  škoda: yes
škoda    strasse: no  škoda: yes

Unicode word boundaries

The ordinary \b boundary lies between a word character and a non-word character. It therefore splits contractions such as don't and decimal numbers. The \b{wb} boundary follows the word rules of the Unicode standard, which know about these cases.

wordbound.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $s = "Don't pay 3.50 for e-mail, it's free.";

say "\\b:     ", join '|', split /\b/, $s;
say "\\b{wb}: ", join '|', split /\b{wb}/, $s;

my @words;
for my $token (split /\b{wb}/, $s) {
    push @words, $token if $token =~ /\w/;
}
say "words: ", join ' ', @words;

Splitting at \b breaks Don't, 3.50 and it's into pieces. Splitting at \b{wb} keeps them whole, and it also keeps spaces and punctuation as separate tokens. The loop keeps only the tokens that contain a word character. The Unicode rules still split e-mail at the hyphen.

$ perl wordbound.pl
\b:     Don|'|t| |pay| |3|.|50| |for| |e|-|mail|, |it|'|s| |free|.
\b{wb}: Don't| |pay| |3.50| |for| |e|-|mail|,| |it's| |free|.
words: Don't pay 3.50 for e mail it's free

Text without spaces

Japanese and Chinese are written without spaces between words. For such text, \w+ matches the whole sentence. Script properties can at least separate runs of different scripts.

nospace.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my $text = '東京のホテルを予約しました';

say "\\w+:            ", join '|', $text =~ /\w+/g;
say "\\p{Han}+:       ", join '|', $text =~ /\p{Han}+/g;
say "\\p{Katakana}+:  ", join '|', $text =~ /\p{Katakana}+/g;
say "\\p{Hiragana}+:  ", join '|', $text =~ /\p{Hiragana}+/g;

The Japanese sentence mixes three scripts: Chinese characters for the words for Tokyo and reservation, katakana for the loan word hotel, and hiragana for the grammatical parts. Each script property extracts its own runs. Real word segmentation for these languages needs a dictionary-based tool.

$ perl nospace.pl
\w+:            東京のホテルを予約しました
\p{Han}+:       東京|予約
\p{Katakana}+:  ホテル
\p{Hiragana}+:  の|を|しました

Best practices

Keep these points in mind when working with Unicode in regular expressions.

Source

perlunicode · perluniprops · perlrebackslash

In this article we have matched letters, general categories and scripts with \p{...}, detected mixed scripts, worked with grapheme clusters, shortened text safely, matched case-insensitively and split text at Unicode word boundaries. See also Perl UTF-8 and encoding and Perl regex modifiers.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.