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

Scala正则匹配失败求助:输入字符串解析返回空结果

Let's figure out why your regex isn't matching and fix it step by step.

What's Wrong with Your Original Code

Your current implementation has a few critical issues that lead to an empty output:

  1. Mismatched regex pattern: The \S{4} segment expects 4 non-whitespace characters, but your input only has LOC (3 characters) in that position. This breaks the entire match.
  2. Overly complex groups: Patterns like (.{6}[^*]) don't align with your input's structure, adding unnecessary complexity and room for error.
  3. Variable name typo: You reference name in your function, but the regex group is named naame (extra 'a') — this would cause an error even if the match succeeded.

Corrected Solution

Let's simplify the regex to target exactly what you need to extract: the fruit name and the numeric value inside the parentheses (with leading zeros stripped). Here's the fixed code:

import scala.util.matching.Regex

val input = " 12 BANANAPPLESTRAWBERRY LOC 8(05)."
// Simplified regex focused on capturing only the necessary parts
val regFixed: Regex = """^\s*\d+\s+(\S+)\s+LOC\s+\d+\(0*(\d+)\)\.*$""".r

def functionEx(s: String, reg: Regex): String = {
  s match {
    case reg(fruitName, length) => s" $fruitName Int($length)"
    case _ => ""
  }
}

// Test the function
println(functionEx(input, regFixed)) // Output: " BANANAPPLESTRAWBERRY Int(5)"

Breakdown of the Fixed Regex

Let's walk through what each part of the regex does:

  • ^\s*\d+\s+: Matches leading whitespace, the initial number (e.g., "12"), and trailing whitespace — we skip this since we don't need it in the output.
  • (\S+): Captures the fruit name (all non-whitespace characters, which works perfectly since your fruit name has no spaces).
  • \s+LOC\s+: Matches the whitespace, "LOC", and subsequent whitespace — another segment we just need to skip.
  • \d+\(0*(\d+)\)\.*: Matches the number before the parentheses (e.g., "8"), the opening parenthesis, any leading zeros, captures the actual numeric value (e.g., "5"), the closing parenthesis, and an optional trailing dot.
  • $: Ensures we match the end of the string to avoid partial matches.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:19:20