SCALA DUMP ZONE

Helper page for Scala snippets

Regex Tester

Result:
    • Start with an input string, call it input.
    • Define a regex pattern, call it pattern, and add .r to the end to convert it into a scala.util.matching.Regex.
    • Define values as val pattern(val1, val2, ...) = input

    This example regex finds the two sentences and saves them as individual values.

    scala> val testString = "I am a sentence. I am another sentence."
    testString: String = I am a sentence. I am another sentence.
    
    scala> val pattern = "^(.*)\\.\\s(.*)\\.$".r
    pattern: scala.util.matching.Regex = ^(.*)\.\s(.*)\.$
    
    scala> val pattern(sentenceOne, sentenceTwo) = testString
    sentenceOne: String = I am a sentence
    sentenceTwo: String = I am another sentence
    • Start with an input string, call it input.
    • Define a regex pattern, call it pattern, and add .r to the end to convert it into a scala.util.matching.Regex.
    • Define values as val output = (pattern.findAllIn(input)) (or use infix notation) and convert it into a List by appending .toList.

    This example regex finds all numbers in a string and puts them in a List.

    scala> val input = "12345 abc abc 67890"
    input: String = 12345 abc abc 67890
    
    scala> val pattern = "\\d".r
    pattern: scala.util.matching.Regex = \d
    
    scala> val ints = (pattern findAllIn input).toList
    ints: List[String] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    • Start with an input string, call it input.
    • Define a regex pattern, call it pattern.
    • Check the string matches with input.matches(regex)

    This example regex is for a valid time for a 24hr clock.

    scala> val regex = "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"
    regex: String = ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
    
    scala> val testStringOne = "12:59"
    testStringOne: String = 12:59
    
    scala> val testStringTwo = "12:60"
    testStringTwo: String = 12:60
    
    scala> testStringOne.matches(regex)
    res0: Boolean = true
    
    scala> testStringTwo.matches(regex)
    res1: Boolean = false