Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

scala regex meaning

i am new to scala and hate regex 😀
cuurently i am debuggig a piece of code

  def validateReslutions(reslutions: String): Unit = {
    val regex = "(\\d+-\\d+[d,w,m,h,y],?)*"
    if (!reslutions.matches(regex)) {
      throw new Error("no match")
    } else {
      print("matched")
    }
  }
  validateReslutions(reslutions = "(20-1w,100-1w)")
}

the problem is it produces no match for this input , so how to correct the regex to match this input

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your (20-1w,100-1w) string contains a pair of parentheses at the start and end, and the rest matches with your (\d+-\d+[d,w,m,h,y],?)* regex. Since String#matches requires a full string match, you get an exception.

Include the parentheses patterns to the regex to avoid the exception:

def validateReslutions(reslutions: String): Unit = {
    val regex = """\((\d+-\d+[dwmhy],?)*\)"""
    if (!reslutions.matches(regex)) {
        throw new Error("no match")
    } else {
        print("matched")
    }
}
validateReslutions(reslutions = "(20-1w,100-1w)")
// => matched

See the Scala demo.

Note the triple quotes used to define the string literal, inside which you can use single backslashes to define literal backslash chars.

Also, mind the absence of commas in the character class, they match literal commas in the text, they do not mean "or" inside character classes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading