Scala动态变量注入实现字符串插值:如何为含不同变量的字符串序列批量替换值?
Got it, let's solve this problem of injecting values into your string placeholders. You've got strings with $Y, $m, $d placeholders, and you need to replace them with actual values dynamically. Here are two practical approaches that work perfectly for your use case:
Approach 1: Simple Chain of replace Calls
This is the most straightforward method, great for when you have a small, fixed set of placeholders. It works seamlessly even if some strings don't include all placeholders (like your s2 missing $d).
First, define your target values (we'll use current date as an example, but you can substitute any custom values):
import java.time.LocalDate val today = LocalDate.now() val year = today.getYear.toString val month = f"${today.getMonthValue}%02d" // Ensures two-digit format (e.g., "09" instead of "9") val day = f"${today.getDayOfMonth}%02d"
Then apply the replacements to each string in your sequence:
val myStringsUpdated: Seq[String] = myStrings.map { s => s.replace("$Y", year) .replace("$m", month) .replace("$d", day) }
Approach 2: Regex + Mapping (More Flexible)
If you anticipate adding more placeholders later, this method scales better. We'll use a regex to match any placeholder and a map to look up their corresponding values.
First, set up your placeholder-to-value mapping:
import java.time.LocalDate val today = LocalDate.now() val placeholderValues = Map( "$Y" -> today.getYear.toString, "$m" -> f"${today.getMonthValue}%02d", "$d" -> f"${today.getDayOfMonth}%02d" )
Next, create a regex that matches any of the placeholders, then use it to replace all matches in each string:
val placeholderRegex = placeholderValues.keys.mkString("(", "|", ")").r val myStringsUpdated: Seq[String] = myStrings.map { s => placeholderRegex.replaceAllIn(s, matchResult => placeholderValues(matchResult.group(0))) }
Key Notes
- Both methods handle strings that don't include all placeholders (like
s2) without extra code—missing placeholders simply remain untouched (which is exactly what you want). - If you don't need current date values, just swap out the
placeholderValuesmap with your custom values (e.g.,Map("$Y" -> "2023", "$m" -> "12", "$d" -> "31")).
内容的提问来源于stack exchange,提问作者Dariusz Krynicki

