qed
qed

Reputation: 23104

Regex pattern matching not working in scala.js?

Here is the code:

val s =
  """
    |\begin{bmatrix}
    |\cos \theta & -\sin \theta \\
    |\sin \theta & \cos \alpha
    |\end{bmatrix}
  """.stripMargin

val lastWordPattern = """(?s)(.*)\s+(.*)""".r
def wordToPos(string: String, position: Int): String = {
  val subString = string.substring(0, position)
  println("sub: ", subString)
  subString match {
    case lastWordPattern(x@_*) => {
      println(0, x(0))
      println(1, x(1))
      x(0)
    }
    case _ => ""
  }
}
wordToPos(s, 20)

Result from sbt console:

scala>     wordToPos(s, 20)
(sub: ,
\begin{bmatrix}
\co)
(0,
\begin{bmatrix})
(1,\co)

Result from chrome:

(sub: ,
\begin{bmatrix}
\co)

In chrome the code prints the substring, but fails to match the regex. Am I doing something wrong?

Upvotes: 3

Views: 407

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

As JavaScript does not support singleline modifier (neither inline, nor a regular one), you need to replace every . outside the character class with [\s\S] (a character class with opposite shorthand classes that matches any symbol there can be in a string).

With [\s\S], you will match any symbol including a newline without the need to specify the singleline mode.

val lastWordPattern = """([\s\S]*)\s+([\s\S]*)""".r

Upvotes: 3

Related Questions