Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

regex for utf-8

by jjohhn (Scribe)
on Feb 27, 2003 at 22:26 UTC ( [id://239273]=perlquestion: print w/replies, xml ) Need Help??

jjohhn has asked for the wisdom of the Perl Monks concerning the following question:

I am new, and faced with converting utf-8 to extended ascii (in one of three flavors: windows-ascii (cp 1252), Latin-1(8859-1), and/or OEM/DOS (cp 437). I found this after much searching:
s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg;
which seems to convert utf-8 to *something* (probably windows-ansi)

Could someone help me understand the expression? The search part I can pretty much get, but the replace has me alittle puzzled. Specifically

  • what is "<<" doing?
  • what is "&" doing?
  • What's going on with the alternation ("|") ?

Thanks.

Replies are listed 'Best First'.
Re: regex for utf-8
by Thelonius (Priest) on Feb 28, 2003 at 00:05 UTC
    Latin-1 (iso-8859-1) is a subset of Unicode. UTF-8 is an algorithic transform of Unicode, which maps characters > 127 to multiple bytes. See rfc2279 for details or the Unicode site.

    If you know that your characters are all from the Latin-1 character set (but in the UTF-8 encoding), you can just do this:

    pack "C*", unpack "U*", $_
    This maps directly to Latin-1. But for other character sets, you'll need table-driven mappings. There are modules that do this. See the Unicode::Map and similar modules on CPAN.

    Here is a quickie which just handles Windows-1252:

    #!perl -w use strict; my %unicode2win1252 = ( 0x0152 => 0x8C, 0x0153 => 0x9C, 0x0160 => 0x8A, 0x0161 => 0x9A, 0x0178 => 0x9F, 0x017D => 0x8E, 0x017E => 0x9E, 0x0192 => 0x83, 0x02C6 => 0x88, 0x02DC => 0x98, 0x2013 => 0x96, 0x2014 => 0x97, 0x2018 => 0x91, 0x2019 => 0x92, 0x201A => 0x82, 0x201C => 0x93, 0x201D => 0x94, 0x201E => 0x84, 0x2020 => 0x86, 0x2021 => 0x87, 0x2022 => 0x95, 0x2026 => 0x85, 0x2030 => 0x89, 0x2039 => 0x8B, 0x203A => 0x9B, 0x20AC => 0x80, 0x2122 => 0x99, ); sub simplemap { my ($map, $str) = @_; pack "C*", map { $$map{$_}||$_ } unpack "U*", $str } my $a = "This is a " . pack("U*", 0x201c) . "test" . pack("U*", 0x201d +) . " Okay, Jos" . pack("U*", 0xe9) . "?" . pack("U*", 0xfeff); # The last character U+FEFF is not in Windows-1252 and is thrown in # as an example of what happens to other characters. my $b = simplemap(\%unicode2win1252, $a); my $c = unpack("H*", $b); print "a = $a\nb = $b\nc = $c\n";
    There are C and Java conversion routines at the ICU project. I derived the hash %unicode2win1252 from the data file data/ibm-5348.ucm. See data/convrtrs.txt for the names of the character sets.
      wow! Why are there only 27 entries in the table? The practical task that I am to do is search on a utf-8 encoded file of tab-delimited strings, and find the non-ascii characters. From there I want to capture one of the tabbed fields (an ID#), the phrase containing the non-ascii character (another tabbed field), and keep a count of how many of each non-ascii character I have. I believe I would need to include something like:
      ... while<FILE>{ if ( /[\x80..\xFF]/ ){ @fields = split /\t/, $_; ($con_id, $desc_id, $string) = @fields[0,1,4]; ...
      but that wouldn't reallycapture non-ascii containing strings, because utf-8 has the multibyte feature for codes >= x80. How can I catch the utf-8 characters that are non-ascii (which are multi-byte encoded)?
        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]

Re: regex for utf-8
by Zaxo (Archbishop) on Feb 27, 2003 at 23:05 UTC

    The /e modifier on your substitution says that the substitute string is to be evaluated as a perl expression. The '<<' operator is 'shift left', corresponding to multiplication by a power of two. The '|' operator is 'bitwise or', not alternation. See perlop for details.

    Update: The & operator is 'bitwise and'.

    After Compline,
    Zaxo

      Hmm. Thank you. Somehow these operations are converting an 8-bit character representaion to a multibyte (UTF-8) representation, for those values that are greater than 7F, and leaving the values alone when they fall within ASCII range. Probably it converts to Latin-1 since I think you would need a lookup table to convert to one of the other encodings. I am still a little over my head here, but I am swimming upwards. What is the "&" doing here? Thanks again
        >> Somehow these operations are converting an 8-bit character representaion to a multibyte (UTF-8) representation

        Actually, the other way around. It converts UTF-8 encoded characters to plain 8-bit numbers, for numbers in the range 0x80 through 0xFF inclusive. It ignores anything outside that range—anything lower is already ASCII, and anything higher is left unchanged, and would leave incorrect stuff in the string.

        Yes, the output is Latin-1, because Unicode's first 256 code points are identical to Latin-1.

Re: regex for utf-8
by John M. Dlugosz (Monsignor) on Feb 27, 2003 at 23:35 UTC
    The match part is:
    ([\xC2\xC3]) ([\x80-\xBF])
    which is exactly two characters. The first is code C2 or C3 (binary 11000010 or 11000011).

    The second is anything in the range 10000000 through 10111111, or 10xxxxxx, which is a continuation byte.

    The "|" is not alternation, since that is not in the pattern but in code. The /e modifier means to evaluate the right-hand-side before replacing.

    Now, what needs to be done is take the last two bits from the first byte (10 or 11) and the low six bits from the second byte (the x's) and make the final byte from that. That's what the shifting and masking is for.

    — John

Re: regex for utf-8
by allolex (Curate) on Feb 27, 2003 at 23:23 UTC

    What Zaxo said.

    I seem to getting a lot of milage out of this advice recently, but have you considered using iconv or recode for this task? These are not Perl anything, but tools designed to convert between character encodings (recode is available for GNU/Linux and Windows--see this link, iconv is distributed with RedHat GNU/Linux distros).

    --
    Allolex

      I did come across recode in my searching. In a addition to doing the task itself (which I can do right now by pouring the text into, converting, and pouring out of either vim, textpad or MS Access 2000), I want to understand this at a deeper level than I do. I also want to know how those three tools are doing the task.
Re: regex for utf-8
by Anonymous Monk on Apr 18, 2010 at 11:52 UTC
    use autodie; use File::BOM; open my($In), '<:encoding(UTF-8):via(File::BOM))', $infile; open my($Out), '>:encoding(Windows-1252)', $outfile; print $Out $_ while <$In>; close $In; close $Out;
    or
    use Encode; binmode STDIN; binmode STDOUT; print encode( 'Windows-1252', decode( 'UTF-8', $_ ) ) while <STDIN>;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://239273]
Approved by John M. Dlugosz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-20 06:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found