You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala列表基于用户输入过滤:如何得到指定匹配结果?

Scala List Filtering: Match Substrings with Exact Match Exclusion

Hey there! Let's work through this list filtering problem in Scala step by step.

First, let's clarify the core requirements from your example:

  • Keep elements that contain the substring "ab"
  • Exclude the element that is exactly equal to "ab" itself (since it's missing from your expected result)

Solution Code

Here's a straightforward implementation using Scala's built-in filter method:

val original = List("a","ab","abc","abcd","zadad","ji","jijdf","bcab", "frab","abkcdef","opabcd")
val find = "ab"
val result = original.filter(s => s.contains(find) && s != find)

Logic Breakdown

  • filter iterates over every element in the list and retains only those that meet our condition
  • s.contains(find) checks if the current string includes the target substring "ab"
  • s != find ensures we exclude the exact match of "ab" (since you don't want this entry in your final result)

More Generic Version

If you want a solution that works for any target substring (not just "ab"), you can replace the exact equality check with a length comparison. This approach automatically excludes any element that's the same length as the target (and thus can only be an exact match):

val result = original.filter(s => s.contains(find) && s.length > find.length)

Verify the Result

Running either snippet will give you the expected output:
List("abc", "abcd", "bcab", "frab", "abkcdef", "opabcd")

内容的提问来源于stack exchange,提问作者Anil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:48:40