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
filteriterates over every element in the list and retains only those that meet our conditions.contains(find)checks if the current string includes the target substring "ab"s != findensures 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
相关产品推荐
相关产品推荐

