in reply to Re: Re: regex for utf-8
in thread regex for utf-8

There are only 27 entries because all the rest of the 256 entries map to themselves (Windows-1252 is a superset of Latin-1.) There are also some fallback entries that could be added that are not bidirectional. And of course there are thousand of Unicode characters that are not in Windows-1252, but what can you do about that?

UTF-8 is multibyte for codes >= x80, but those multiple bytes always have the high bit set! That's one of the nice features of UTF8. Of course you meant to say [\x80-\xff]. You can also easily tell the number of bytes per character just by looking at the first byte. See this table from RFC2279:

UCS-4 range (hex.) UTF-8 octet sequence (binary) 0000 0000-0000 007F 0xxxxxxx 0000 0080-0000 07FF 110xxxxx 10xxxxxx 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx
If the high bit is set, then the number of consecutive ones following that is the number of bytes that follow. And all of those start with "10" so you can't confuse them with ASCII characters or with a leading byte of a UTF-8 sequence. Pretty easy!

If you notice, the lead byte of a multibyte sequence is going to be in the range [\xc0-\xfd]

Replies are listed 'Best First'.
Re: Re: Re: Re: regex for utf-8
by Anonymous Monk on Feb 28, 2003 at 05:13 UTC
    I am wrapping my head around the bit-masking and conditional bit-shifting I need to do to extract the actual value of the code. The czyborra site http://czyborra.com/utf/ is invaluable, but my head is thick. How do I march down from the high bit of the first byte, testing and then extracting the hex codes from the succeeding bits?
      I am wrapping my head around the bit-masking and conditional bit-shifting I need to do to extract the actual value of the code. The czyborra site http://czyborra.com/utf/ is invaluable, but my head is thick. How do I march down from the high bit of the first byte, testing and then extracting the hex codes from the succeeding bits?
      That's what unpack "U*" does.
        I have RTFM'ed pack() and unpack(), but don't understand its use in this context. What is the "TEMPLATE" being used here?
        unpack TEMPLATE,EXPR unpack does the reverse of pack: it takes a string and expands it out +into a list of values. (In scalar context, it returns merely the firs +t value produced.)
        This line in the manual I find obscure as well, though it seems it would help me if I understood it:
        sub ordinal { unpack("c",$_[0]); } # same as ord()
        Could you explain unpack "U*"? What is the "U"? (something to do with Unicode? I listened to "Well you needn't" (angular piano music)last night in celebration of the post showing the table for converting with cp 1252