How to match a string not containing a substring using RegEx in Scala

1 Answer

0 votes
import scala.util.matching.Regex

// ^: Matches the beginning of the string
// (?!notype): asserts that the current position in the string is not followed by the 
//             substring "notype"
// .: Matches any single character (except newline characters)
// *: Matches the preceding group (((?!notype).)) zero or more times
// $: Matches the end of the string

object StringNotContainingSubstring {
  def stringNotContainingSubstring(pattern: String, text: String): Boolean = {
    val re = new Regex(pattern, "i")
    
    re.findFirstIn(text).isDefined
  }

  def main(args: Array[String]): Unit = {
    val pattern = "^((?!notype).)*$"

    println(stringNotContainingSubstring(pattern, " notype"))
    println(stringNotContainingSubstring(pattern, "notype "))
    println(stringNotContainingSubstring(pattern, "notypevar"))
    println(stringNotContainingSubstring(pattern, "anotypevar"))
    println(stringNotContainingSubstring(pattern, "anotype"))
    println(stringNotContainingSubstring(pattern, "The only approval you need is your own"))
    println(stringNotContainingSubstring(pattern, "follow your dreams"))
    println(stringNotContainingSubstring(pattern, "Never regret anything that made you smile"))
    println(stringNotContainingSubstring(pattern, "A programming language"))
  }
}



/*
run:

false
false
false
false
false
true
true
true
true
 
*/

 



answered Feb 28, 2025 by avibootz
edited Feb 28, 2025 by avibootz

Related questions

...