Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Unicode substitution regex conundrum

by Polyglot (Pilgrim)
on Oct 16, 2007 at 09:59 UTC ( #645145=perlquestion: print w/replies, xml ) Need Help??
Polyglot has asked for the wisdom of the Perl Monks concerning the following question:


I am writing an interface for a search engine that will pull its results from a database. I have, more or less, mastered the entire code in English, and am now trying to remaster it in CJK-compatible fonts. I would prefer to use uft8, and ideally the solution should be compatible with standard Latin characters as well. I am using Perl 5.8.7.

At the core of the problem is that I am unable to get a pattern match for words in a unicode-containing string. Even if I place spaces between the words, the regex will not recognize the space. I have tried \s \p{IsSpace} \P{IsWord} \b \X \p{IsZ} \p{IsZc} and others, with or without "use Encode;" or "use utf8;" in various forms, all to no avail. Here is an example of one line of my code:

1 while $line =~ s/(\p{IsWord})(?<!\p{IsSpace}AND|\p{IsSpace}XOR|\p{ +IsSpace}NOT|\p{IsWord}\p{IsSpace}OR)(\p{IsSpace}|\s|\p{IsMc}|\p{IsZs} +|\p{IsZ})(?!AND\p{IsSpace}|XOR\p{IsSpace}|NOT\p{IsSpace}|\&\&|\&\p{Is +Space}|\+|\|\||\||OR\p{IsSpace}|\^|\!)(\p{IsWord})/$1 AND $3/gi;
Now, that line will function perfectly on an English input string, but as soon as I enter Chinese, it won't match anything. All that line needs to do is to insert an " AND " between any two spaced words, after verifying that those words are not search operator terms themselves. So, XXX YYY OR ZZZ should become XXX AND YYY OR ZZZ.

Any ideas for why this is not performing correctly in utf8? (I'm open to a total rewrite of the line, as it's obvious I haven't found the best solution yet.)

Thank you!

Replies are listed 'Best First'.
Re: Unicode substitution regex conundrum
by Juerd (Abbot) on Oct 16, 2007 at 10:55 UTC

    "use utf8;" is needed if your source code is actually in UTF8 encoding. It does not affect regex matches.

    Perl does not have UTF8 semantics, but instead Unicode semantics. The difference is that you work on *encodingless* strings in Perl, and that you use *normal* operators instead of separate ones. The important things are done internally.

    Please read the Perl Unicode Tutorial and the Perl Unicode FAQ.

    The following ought to suffice:

    # untested! use Encode qw(decode); use Unicode::Semantics qw(up); up($line = decode 'UTF-8', $line); my $word = qr/\b(?!(?:AND|OR|XOR|NOT)\b)\w+/i; $line =~ s/($word)\s*($word)/$1 AND $2/g for 1..2;
    Unicode::Semantics works around a bug that causes the second half of latin1 to be ignored under certain circumstances.

    Juerd # { site => '', do_not_use => 'spamtrap', perl6_server => 'feather' }

      Thank you for the helpful responses. I learned several new things. However, I am still unable to get my program functioning correctly.

      For starters, I am not opening a file. I am receiving the utf8 input from an HTML form, and, quite frankly, I have no way of knowing whether user input will be received in the Perl script as utf8, unicode, big5, gb2312, etc., although I am trying to work solely with utf8. The database being searched is in utf8, but Perl is doing next to nothing with it once received with the DBI commands, other than outputting it back to HTML.

      On your advice, I tried learning more about utf8, and have tried using the -COE command in the shebang line (this rendered the output unreadable), and I tried using the Encode qw(encode decode), to no avail.

      Here are my current uses:

      use CGI; use CGI::Carp qw(fatalsToBrowser); use strict; use DBI; use Encode; use Encode qw(_utf8_on); use Encode::HanConvert; #Module for dealing with CJK conversions use Encode qw(encode decode); require Encode::CN; require Encode::TW;
      So I am still left wondering how to make perl see the string as utf8. Am I missing something? Is Perl 5.8.7 recent enough? How can I flag utf8 on input from a form rather than a file?

      The real puzzle, to me, is that split// seems to work, but the s/// won't work. Unfortunately, I have no way of knowing how many terms the user will be entering, so using split would require some significant recoding. Thank you!

        If you don't know the encoding of data, how shall perl know it?

        When you don't set CGIs charset parameter, it will return a byte string, that you have to convert to perl's internal format... but I wrote that already.

        You can try to use Encode::Guess if you have a few possible charsets that aren't too similar and your input data is long enough.

        If this doesn't hold true you have to take care that your input will be in a known encoding, for example in HTML forms you can set the accept-charset attribute to utf8 only.

        And when you want unicode semantics in regex matches, check with encode::is_utf8($string) that it is indeed in perl's internal format.

      This is late, but I do have the script working well now, and I wanted to say a big thank you to those of you who offered your support. Juerd was probably closest to the solution that seemed to fit best in my situation.

      For those who may be seeking the same wisdom, I would like to post the full solution in my case.

      My entire "use" section:

      use CGI; use CGI::Carp qw(fatalsToBrowser); use strict; use DBI; use Encode; use Encode::HanConvert; #Module for dealing with CJK conversions use Encode qw(encode decode); use POSIX qw(locale_h); require Encode::CN; require Encode::TW; require 5.004;
      For incoming form values:
      $name = decode("utf-8", $name); $value = decode("utf-8", $value);
      For incoming values from the database:
      my $quest = $dbh->prepare($statement, { RaiseError => 1 }) or die "Cannot prepare statement! $DBI::errstr\n"; while(@row = $quest->fetchrow_array()) { $c1=shift @row; $c1=decode("utf-8", $c1); ... }
      And finally, an example of the regex which now functions on multiple languages (UTF8):
      $line =~ s%(?:\p{IsSpace}*) #Match zero or more spaces (\bNOT)? #Match zero or one "NOT" operator(s) (\(*) #Match zero or more left parentheses (\p{IsSpace}*|\s*|\b|^) #Match zero+ spaces or a word boundary (?!\") #Ensure this doesn't appear beforehand ((?:\p{IsWord}|\w|`| #Match zero+ words (?:\&\p{IsAlnum}*\;)*)* #Include HTML special chars, e.g. &aacute; (?:\.\{\d+\})* #Include zero+ MySQL-style wildcard '?'s (?:\[\.[^\.\]]*\.\])* #Include zero+ MySQL REGEXP chars (?:\[\:[^\:\]]*\:\])* #Include zero+ MySQL REGEXP special chars (?:\[[^\]]*\])* #Incl. zero+ MySQL REGEXP special patterns (?:\*(?!\"))* #Include zero+ stand-alone asterisks (?:\%(?!\"))* ) #Include zero+ stand-alone percent signs (?:\s*|\p{IsSpace}*) #Match zero+ spaces (\)*) #Match zero+ right parentheses (?:\p{IsSpace}|\s)* #Match zero+ spaces (["()]*) #Match zero+ double quotes or parentheses (?:\p{IsSpace}*) #Match zero+ spaces ( #(begin group) (?:NOT|OR|AND|XOR)* #Match zero+ operator words (?:\p{IsSpace}+|\(+|\p{IsZ}|\Z) #Then one+ spaces OR one+ ")" #OR end-of-string ) #(end group) #AND SUBSTITUTE THE ABOVE WITH THE BELOW %$2$3$table\.$columnName`$1`$like`"$l$wb$4$we$l"$5$6 $7 %xig;
      Again, thank you very much! And thank you to Moritz who prodded me to learn how to code the regex substitution on multiple lines, with comments for readability. Blessings!


        That "use 5.004" is useless; Encode already requires 5.8. I recommend using "use 5.8.3;" or "use 5.008003";

Re: Unicode substitution regex conundrum
by moritz (Cardinal) on Oct 16, 2007 at 10:24 UTC
    I hope this is no production code...?

    The regex is totally unreadable, you should use the /x modifier and align and comment the regex.

    Now to the core of the problem: You need to convert the strings into perl's internal format before doing a regex match on them. You can do this with Encode::decode.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://645145]
Approved by Corion
[hippo]: s/.*here//;
LanX Eily: Ma digarezit !

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (13)
As of 2018-07-17 13:32 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (367 votes). Check out past polls.