UFO ET IT

Scala에서 더 나은 문자열 포맷팅

ufoet 2021. 1. 5. 08:26
반응형

Scala에서 더 나은 문자열 포맷팅


인수가 너무 많으면 String.format쉽게 혼란스러워집니다. 문자열을 형식화하는 더 강력한 방법이 있습니까? 이렇게 :

"This is #{number} string".format("number" -> 1)

또는 유형 문제로 인해 가능하지 않습니까 ( formatMap [String, Any]를 가져와야 할 것입니다. 이것이 상황을 악화 시킬지 모르겠습니다).

또는 다음과 같이 더 좋은 방법입니다.

val number = 1
<plain>This is { number } string</plain> text

이름 공간을 더 럽히더라도?

편집하다:

간단한 포주가 많은 경우에 할 수 있지만, 파이썬과 같은 방향으로 진행되는 것을 찾고 있습니다 format()(참조 : http://docs.python.org/release/3.1.2/library/string.html#formatstrings )


Scala 2.10에서는 문자열 보간을 사용할 수 있습니다 .

val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall")  // James is 1.90 meters tall

글쎄요, 당신의 유일한 문제가 매개 변수의 순서를 더 유연하게 만드는 것이라면 이것은 쉽게 할 수 있습니다 :

scala> "%d %d" format (1, 2)
res0: String = 1 2

scala> "%2$d %1$d" format (1, 2)
res1: String = 2 1

또한지도의 도움으로 정규식을 대체 할 수 있습니다.

scala> val map = Map("number" -> 1)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map((number,1))

scala> val getGroup = (_: scala.util.matching.Regex.Match) group 1
getGroup: (util.matching.Regex.Match) => String = <function1>

scala> val pf = getGroup andThen map.lift andThen (_ map (_.toString))
pf: (util.matching.Regex.Match) => Option[java.lang.String] = <function1>

scala> val pat = "#\\{([^}]*)\\}".r
pat: scala.util.matching.Regex = #\{([^}]*)\}

scala> pat replaceSomeIn ("This is #{number} string", pf)
res43: String = This is 1 string

Scala-Enhanced-Strings-Plugin이 도움이 될 수 있습니다. 이봐:

Scala-Enhanced-Strings-Plugin 문서


보다 풍부한 서식을 직접 쉽게 구현할 수 있습니다 (pimp-my-library 접근 방식 사용).

scala> implicit def RichFormatter(string: String) = new {
     |   def richFormat(replacement: Map[String, Any]) =
     |     (string /: replacement) {(res, entry) => res.replaceAll("#\\{%s\\}".format(entry._1), entry._2.toString)}
     | }
RichFormatter: (string: String)java.lang.Object{def richFormat(replacement: Map[String,Any]): String}

scala> "This is #{number} string" richFormat Map("number" -> 1)
res43: String = This is 1 string

이것은 내가 여기에서 찾고있는 대답입니다.

"This is %s string".format(1)

2.10을 사용하는 경우 기본 제공 보간을 사용하십시오. 그렇지 않으면 극단적 인 성능에 신경 쓰지 않고 기능적인 한 줄짜리를 두려워하지 않는다면 fold + 여러 regexp 스캔을 사용할 수 있습니다.

val template = "Hello #{name}!"
val replacements = Map( "name" -> "Aldo" )
replacements.foldLeft(template)((s:String, x:(String,String)) => ( "#\\{" + x._1 + "\\}" ).r.replaceAllIn( s, x._2 ))

정말 복잡하고 긴 문자열에 템플릿 엔진 사용을 고려할 수도 있습니다. 내 머리 위에는 Mustache 템플릿 엔진 을 구현하는 Scalate있습니다.

Might be overkill and performance loss for simple strings, but you seem to be in that area where they start becoming real templates.

ReferenceURL : https://stackoverflow.com/questions/4051308/better-string-formatting-in-scala

반응형