21

I am trying to scrap a unicode string using javascript. Said string could countain mixed characters. Example: 我的中文不好。我是意大利人。你知道吗?

Ultimately, the string may contain - Chinese characters - Chinese punctuation - ANSI characters and punctuation

I need to leave the Chinese characters only . Any hint ?

Sujith PS
  • 4,776
  • 3
  • 34
  • 61
resle
  • 2,254
  • 4
  • 19
  • 37
  • 1
    I'm late, but here is the commonly used Chinese characters range: `\u4E00-\u9FA5`, which contains around 26000 characters, which should be enough for daily use. – Raptor Aug 10 '15 at 12:16
  • @Raptor Is this ? part of the CJK char? If so which range it exists? – Helen Araya Jun 11 '20 at 22:34
  • 1
    yes, this is a Chinese question mark. You can use this tool to lookup its Unicode value: https://r12a.github.io/app-conversion/ – Raptor Jun 12 '20 at 02:28

4 Answers4

41

You can see the relevant blocks at http://www.unicode.org/reports/tr38/#BlockListing or http://www.unicode.org/charts/ .

If you are excluding compatibility characters (ones which should no longer be used), as well as strokes, radicals, and Enclosed CJK Letters and Months, the following ought to cover it (I've added the individual JavaScript equivalent expressions afterward):

  • CJK Unified Ideographs (4E00-9FCC) [\u4E00-\u9FCC]
  • CJK Unified Ideographs Extension A (3400-4DB5) [\u3400-\u4DB5]
  • CJK Unified Ideographs Extension B (20000-2A6D6) [\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6]
  • CJK Unified Ideographs Extension C (2A700-2B734) \ud869[\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34]
  • CJK Unified Ideographs Extension D (2B840-2B81D) \ud86d[\udf40-\udfff]|\ud86e[\udc00-\udc1d]
  • 12 characters within the CJK Compatibility Ideographs (F900-FA6D/FA70-FAD9) but which are actually CJK unified ideographs [\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]

...so, a regex to grab the Chinese characters would be:

/[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]/

Due in fact to the many CJK (Chinese-Japanese-Korean) characters, Unicode was expanded to handle more characters beyond the "Basic Multilingual Plane" (called "astral" characters), and since the CJK Unified Ideographs extensions B-D are examples of such astral characters, those extensions have ranges that are more complicated because they have to be encoded using surrogate pairs in UTF-16 systems like JavaScript. A surrogate pair consists of a high surrogate and a low surrogate, neither of which is valid by itself but when joined together form an actual single character despite their string length being 2).

While it would probably be easier for replacement purposes to express this as the non-Chinese characters (to replace them with the empty string), I provided the expression for the Chinese characters instead so that it would be easier to track in case you needed to add or remove from the blocks.

Update September 2017

As of ES6, one may express the regular expressions without resorting to surrogates by using the "u" flag along with the code point inside of the new escape sequence with brackets, e.g., /^[\u{20000}-\u{2A6D6}]*$/u for "CJK Unified Ideographs Extension B".

Note that Unicode too has progressed to include "CJK Unified Ideographs Extension E" ([\u{2B820}-\u{2CEAF}]) and "CJK Unified Ideographs Extension F" ([\u{2CEB0}-\u{2EBEF}]).

For ES2018, it appears that Unicode property escapes will be able to simplify things even further. Per http://2ality.com/2017/07/regexp-unicode-property-escapes.html , it looks like will be able to do:

/^(\p{Block=CJK Unified Ideographs}|\p{Block=CJK Unified Ideographs Extension A}|\p{Block=CJK Unified Ideographs Extension B}|\p{Block=CJK Unified Ideographs Extension C}|\p{Block=CJK Unified Ideographs Extension D}|\p{Block=CJK Unified Ideographs Extension E}|\p{Block=CJK Unified Ideographs Extension F}|[\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29])+$/u

And as the shorter aliases from http://unicode.org/Public/UNIDATA/PropertyAliases.txt and http://unicode.org/Public/UNIDATA/PropertyValueAliases.txt can also be used for these blocks, you could shorten this to the following (and changing underscores to spaces or casing apparently too if desired): /^(\p{blk=CJK}|\p{blk=CJK_Ext_A}|\p{blk=CJK_Ext_B}|\p{blk=CJK_Ext_C}|\p{blk=CJK_Ext_D}|\p{blk=CJK_Ext_E}|\p{blk=CJK_Ext_F}|[\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29])+$/u

And if we wanted to improve readability, we could document the falsely labeled compatibility characters using named capture groups (see http://2ality.com/2017/05/regexp-named-capture-groups.html ):

/^(\p{blk=CJK}|\p{blk=CJK_Ext_A}|\p{blk=CJK_Ext_B}|\p{blk=CJK_Ext_C}|\p{blk=CJK_Ext_D}|\p{blk=CJK_Ext_E}|\p{blk=CJK_Ext_F}|(?<CJKFalseCompatibilityUnifieds>[\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]))+$/u

And as it looks per http://unicode.org/reports/tr44/#Unified_Ideograph like the "Unified_Ideograph" property (alias "UIdeo") covers all of our unified ideographs and excluding symbols/punctuation and compatibility characters, if you don't need to pick and choose out of the above, the following may be all you need:

/^\p{Unified_Ideograph=yes}*$/u

or in shorthand:

/^\p{UIdeo=y}*$/u

Update April 2023

It seems that JavaScript has yet to support Block/blk as one of the acceptable property aliases: see Table 65 of https://tc39.es/ecma262/multipage/text-processing.html#table-nonbinary-unicode-properties for the currently allowable non-binary properties.

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
  • 1
    Thanks. I did an automated test using 40+ mb of chinese ebooks and in 91% of the cases this /[^\u4E00-\u9FA5]/ig seems to be enough to scrap the text without eating any non-punctuation characters. Looks like most of the characters in other ranges are used quite seldomly. – resle Jan 15 '14 at 10:17
  • 3
    Question: how does the 0x20000-0x2A6D6 range (CJK Extension B) map to that Javascript regexp, `[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6]`? – Ahmed Fasih Aug 25 '14 at 04:17
  • That link is a useful tool... The new String method [String.fromCodePoint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint), allows conversion from the full hex point (e.g., 0x20000) into the actual character (which in JS is expressed as two characters, so you could use `.charCodeAt(0).toString(16)` and `.charCodeAt(1).toString(16)` on the resulting string each individual surrogate character has the expected numeric value). There is also a polyfill there so you can see how older browsers could determine the surrogates. – Brett Zamir Aug 25 '14 at 05:50
  • Whenever you have a range of astral characters, once you know the starting and ending range surrogates, you will need 1-3 alternated range pairs (at least until full Unicode support may be added to JS regexes)--i.e., fewer than 3 pairs if the range begins with the lowest high surrogate or ends with the highest low surrogate, and only one pair if a single (high) surrogate is needed. – Brett Zamir Aug 25 '14 at 05:54
  • 1
    For anyone reading this- this doesn't contain Chinese punctuation. – 0fnt Oct 09 '16 at 19:29
  • 1
    @0fnt for Chinese punctuation you may refer to my question https://stackoverflow.com/questions/76070986/get-chinese-punctuation-in-a-string – Qiulang Apr 22 '23 at 12:12
  • @`AhmedFasih` : @`Brett Zamir`'s mapping is corectt. I ran those 2 through my own encoder, and got these : `0x20000 x40xD8x00xDC xD8x40xDCx00` :::::::::: ::::::::::::::::::::: :::::: :::::::::: ::::::::::::::::::::: : `0x2A6D6 x69xD8xD6xDE xD8x69xDExD6` ::::::::::::::: middle column being little endian, right column being big endian. Their big endian octal dumps are `\330\100\334\000` and `\330\151\336\326` respectively – RARE Kpop Manifesto May 31 '23 at 07:51
28

As of Chrome 64, Firefox 78, Safari 11.1, and Edge 79, the simplest regex to test whether a string is a Chinese character is /\p{Script=Han}/u. The \p{} specifies a Unicode property escape, the Script=Han expression matches any character whose script property is Han (Chinese), and the u flag enables usage of Unicode features in the regex, such as these property escapes.

So you could filter all of the non-Chinese characters from a string like this:

console.log(
    "hello! 42 我的中文不好。我是意大利人。你知道吗?"
        .split("")
        .filter(char => /\p{Script=Han}/u.test(char))
        .join("")
);

The Script property name can also be abbreviated, as in /\p{sc=Han}/u.

jdunning
  • 1,356
  • 1
  • 14
  • 26
1

A copy and paste solution. Uses ES6's unicode flag. All current extensions, up to Extension F, and the Ideographs.

const character_xp = new RegExp(String.raw`
    [\u{FA0E}\u{FA0F}\u{FA11}\u{FA13}\u{FA14}\u{FA1F}\u{FA21}\u{FA23}\u{FA24}\u{FA27}-\u{FA29}]
    |[\u{4E00}-\u{9FCC}]
    |[\u{3400}-\u{4DB5}]
    |[\u{20000}-\u{2A6D6}]
    |[\u{2A700}-\u{2B734}]
    |[\u{2B740}-\u{2B81D}]
    |[\u{2B820}-\u{2CEAF}]
    |[\u{2CEB0}-\u{2EBEF}]
  `.replace(/\s+/g, ''), "u")
Twifty
  • 3,267
  • 1
  • 29
  • 54
0

Rather than inventing your own solution you could probably use unicode-data module (one of the modules generated by it, to be precise), which is essentially a javascript interface to UnicodeData.txt database (akin to unicodedata standard module in python, if it rings your bell).

tutturu
  • 21
  • 1