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:
- Mismatched regex pattern: The
\S{4}segment expects 4 non-whitespace characters, but your input only hasLOC(3 characters) in that position. This breaks the entire match. - Overly complex groups: Patterns like
(.{6}[^*])don't align with your input's structure, adding unnecessary complexity and room for error. - Variable name typo: You reference
namein your function, but the regex group is namednaame(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
相关产品推荐
相关产品推荐

