简体   繁体   English

如何在scala中通过分隔符拆分字符串?

[英]How to split string by delimiter in scala?

I have a string like this:我有一个这样的字符串:

val str = "3.2.1"

And I want to do some manipulations based on it.我想根据它做一些操作。

I will share also what I want to do and it will be nice if you can share your suggestions:我也会分享我想做的事情,如果你能分享你的建议会很好:

im doing automation for some website, and based on this string I need to do some actions.我正在为一些网站做自动化,基于这个字符串我需要做一些动作。

So:所以:

the first digit - I will need to choose by value: value="str[0]"第一个数字 - 我需要按值选择: value="str[0]"

the second digit - I will need to choose by value: value="str[0]+"."+str[1]"第二个数字 - 我需要按值选择: value="str[0]+"."+str[1]"

the third digit - I will need to choose by value: value="str[0]+"."+str[1]+"."+str[2]"第三个数字 - 我需要按值选择: value="str[0]+"."+str[1]+"."+str[2]"

as you can see the second field i need to choose is the name firstdigit.seconddigit and the third field is firstdigit.seconddigit.thirddigit如您所见,我需要选择的第二个字段是名称 firstdigit.seconddigit,第三个字段是 firstdigit.seconddigit.thirddigit

You can use pattern matching for this. 您可以为此使用模式匹配。 First create regex: 首先创建正则表达式:

@ val pattern = """(\d+)\.(\d+)\.(\d+)""".r
pattern: util.matching.Regex = (\d+)\.(\d+)\.(\d+)

then you can use it to pattern match: 那么您可以使用它来进行模式匹配:

@ "3.4.342" match { case pattern(a, b, c) => println(a, b, c) } 
(3,4,342)

if you don't need all numbers you can for example do this 如果您不需要所有数字,例如可以这样做

"1.2.0" match { case pattern(a, _, _) => println(a) }
1

if you want to for example to take just first two numbers you can do 例如,如果您只想取前两个数字,则可以

@ val twoNumbers = "1.2.0" match { case pattern(a, b, _) => s"$a.$b" }
twoNumbers: String = "1.2"

Try the following: 请尝试以下操作:

 scala> "3.2.1".split(".")
 res0: Array[java.lang.String] = Array(string1, string2, string3)

This one: 这个:

object Splitter {
  def splitAndAccumulate(string: String) = {
    val s = string.split("\\.")
    s.tail.scanLeft(s.head){ case (acc, elem) =>
      acc + "." + elem
    }
  }
}

passes this test: 通过此测试:

test("Simple"){
  val t = Splitter.splitAndAccumulate("1.2.3")

  val answers = Seq("1", "1.2", "1.2.3")

  t.zip(answers).foreach{ case (l, r) =>
    assert(l == r)
  }
}

Can only add to @Lukasz's answer one more variant with the values extration: 只能在@Lukasz的答案中添加附加值的一个变体:

@  val pattern = """(\d+)\.(\d+)\.(\d+)""".r 
pattern: scala.util.matching.Regex = (\d+)\.(\d+)\.(\d+)

@  val pattern(firstdigit, seconddigit, thirddigit) = "3.2.1" 
firstdigit: String = "3"
seconddigit: String = "2"
thirddigit: String = "1"

This way all the values can be treated as regular val s further in the code. 这样,所有值都可以在代码中进一步视为常规val

   val str="vaquar.khan"
   val strArray=str.split("\\.")
   strArray.foreach(println)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM