3

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?

2
  • 2
    I think it is because JS does not support (?s) modifier. Try replacing all . with [\s\S] and retry. Commented Nov 7, 2015 at 15:13
  • Indeed, that solves the problem. Commented Nov 7, 2015 at 15:14

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.