scalajs regular expression with Unicode property \\pL or \\p{L}

Viewed 68

Need a regular expression for a letter in any language. \pL or \p{L} work within Ammonite Repl 1.6.8 (Scala 2.13.0 Java 11.0.8)

@ "\\pL+".r.findFirstIn("abcßäöñ") 
res1: Option[String] = Some("abc\u00df\u00e4\u00f6\u00f1")

@ "\\p{L}+".r.findFirstIn("abcßäöñ") 
res2: Option[String] = Some("abc\u00df\u00e4\u00f6\u00f1")

But the Unicode property does NOT work in Scalajs (1.5.1), i.e. result None. Any help appreciated. Thanks

3 Answers

You can change the target ECMAScript version, change it in the following setting:

scalaJSLinkerConfig ~= (_.withESFeatures(_.withESVersion(ESVersion.ES2018)))

Also, you might need to add val ESVersion = org.scalajs.linker.interface.ESVersion in your build.sbt.

Then you can use

"(?U)\\p{L}+".r.findFirstIn("abcßäöñ")
"(?U)[^\\W\\d_]+".r.findFirstIn("abcßäöñ")
"(?U)\\p{Alpha}+".r.findFirstIn("abcßäöñ")

The (?U) flag is the UNICODE_CHARACTER_CLASS embedded flag option that makes \w, \s, \p{Alpha} etc. classes Unicode aware. [^\W\d_] is a class that matches any word chars other than digits and underscores, so basically, letters. \p{Alpha}/\p{L} will match letters only.

Ok, Unicode not supported in the docs

Since Scala.js 1.7.0, Unicode properties, such a \p{L} or its short form \pL, are conditionally supported. They are supported only with the following sbt setting:

scalaJSLinkerConfig ~= (_.withESFeatures(_.withESVersion(ESVersion.ES2018)))

(If using another build tool, please consult that build tool's way of specifying Scala.js linking options.)

With that setting enabled, the only \p{x} properties that are not supported are the ones where x is of the form In and where represents a Unicode block. L is not of the form In..., so it is supported.

Reference: the Scala.js documentation on regex support:

Conditionally supported

[...]

The following features require esVersion >= ESVersion.ES2018 (which is false by default):

  • [...]
  • \p{} expressions where is not one of the POSIX character classes.
Related