How do I check if a string contains a substring in EK9?
← Common String Operations · Ref: Q171
EK9 uses the contains operator for substring checks and matches for regex pattern matching.
CONTAINS OPERATOR
Check if a string contains a substring:
if sentence contains "fox" stdout.println("Found fox")
Returns Boolean. Case-sensitive.
IS IN / IS NOT IN
Natural language syntax:
if "fox" is in sentence stdout.println("Found") if "wolf" is not in sentence stdout.println("Not found")
MATCHES (REGEX)
For pattern-based searching:
if sentence matches /[Ff]ox/ stdout.println("Matches fox pattern")
See Q37 for string basics. See Q33 for regular expressions.
Example
defines module qa.stringops.contains defines program StringContainsDemo() stdout <- Stdout() sentence <- "The Quick Brown Fox Jumps" // === CONTAINS OPERATOR === stdout.println(`Contains 'Brown': ${sentence contains "Brown"}`) stdout.println(`Contains 'wolf': ${sentence contains "wolf"}`) // === IS IN / IS NOT IN === if "Quick" is in sentence stdout.println("Found Quick") if "wolf" is not in sentence stdout.println("wolf not found") // === MATCHES (REGEX) === if sentence matches /.*Fox.*/ stdout.println("Matches Fox pattern") if sentence matches /.*[Bb]rown.*/ stdout.println("Matches Brown pattern (case flexible)") // Case-sensitive contains stdout.println(`Contains 'quick' (lowercase): ${sentence contains "quick"}`) stdout.println(`Contains 'Quick' (correct case): ${sentence contains "Quick"}`)
Common mistakes
E50060 — String has no indexOf() method. Use the contains operator for substring checks. See ek9 -h E50060 for details.
Incorrect:
sentence.indexOf("Brown") >= 0
Correct:
sentence contains "Brown"
Other ways to ask this
- How do I search for text within a string in EK9?
- What is the EK9 equivalent of string.contains()?
- How do I check if a string includes a substring in EK9?
Coming from another language?
Java: str.contains(sub), str.matches(regex). Python: sub in str, re.search(). Rust: str.contains(sub). Go: strings.Contains(str, sub). JavaScript: str.includes(sub), str.match(regex). Kotlin: sub in str, str.contains(sub). EK9: str contains sub, sub is in str, str matches /pattern/.
Keywords: indexOf, match, search, substring, check, includes, find, string, contains, text