Support for Unicode and BOM of Unicode in Regex

Source: Internet
Author: User
We know that the regular expression can use \ uxxxx to represent Unicode encoding, for example, [\ u4e00-\ u9fa5] To represent double-byte characters.

BlogA friend left a message asking me how Regex supports Unicode. So I want to extract the Unicode code of a Chinese character and write it to the Pattern of Regex to illustrate this problem. String s = "medium ";
Byte [] bs = Encoding. Unicode. GetBytes (s );
For (int I = 0; I <bs. Length; I ++)
{
Console. Write (bs [I]. ToString ("X "));
}

The returned result is 2D4E,
Then I write the regular expression to match it.

String s = "medium ";
Regex reg = new Regex (@ "\ u2d4e", RegexOptions. Compiled );
WL (reg. IsMatch (s ));

The returned result is False !!

After thinking for a long time, remember that the bytes of Unicode are stored in the first high and lower (the previous byte is put high and the last byte is put low) and the former is low and the latter is high.

String s = "medium ";
Regex reg = new Regex (@ "\ u4e2d", RegexOptions. Compiled );
WL (reg. IsMatch (s ));

In this case, True is returned.

Later, check Encoding unicode = Encoding. Unicode;

// Get the byte order mark (BOM) of the Unicode encoder.
Byte [] preamble = unicode. GetPreamble ();

If (preamble [0] = 0xFE & preamble [1] = 0xFF)
{
Console. WriteLine ("The Unicode encoder is encoding in big-endian order .");
}
Else if (preamble [0] = 0xFF & preamble [1] = 0xFE)
{
Console. WriteLine ("The Unicode encoder is encoding in little-endian order .");
}

The Unicode encoding in. NET adopts the little-endian sequence by default.

You can see the knowledge of complement encoding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.