Trimming strings in Scala

前端 未结 5 1954
无人共我
无人共我 2020-12-25 10:19

How do I trim the starting and ending character of a string in Scala

For inputs such as \",hello\" or \"hello,\", I need the output as

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-25 11:11

    Someone requested a regex-version, which would be something like this:

    val result = " , ,, hello, ,,".replaceAll("""[,\s]+(|.*[^,\s])[,\s]+""", "'$1'")
    

    Result is: result: String = hello

    The drawback with regexes (not just in this case, but always), is that it is quite hard to read for someone who is not already intimately familiar with the syntax. The code is nice and concise, though.

提交回复
热议问题