如何从Scala中的字符串中的特定字符中删除子字符串

时间:2018-07-06 19:08:01

标签: scala

我想删除“ Y”字符后的子字符串。在以下所有三种情况下,最终输出应为EBAY。但是输出是EBAYSK。

object AndreaTest extends SparkSessionWrapper {
def main(args: Array[String]): Unit = {
  var string1= "EBAY-SK"
  var string2= "EBAY SK"
  var string3= "EBAY- SK"
  val finalString1 = string1.replaceAll("[-]/' '", "")
  val finalString2 = string2.replaceAll("[-]/' '", "")
  val finalString3 = string3.replaceAll("[-]/' '", "")
  println(finalString1)
  println(finalString2)
  println(finalString3)
}

2 个答案:

答案 0 :(得分:2)

尝试此正则表达式

x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam']
loc = []
new_x = []

for name in x:
    if x.count(name) == 1:
        loc.append(1)
    else:
        loc.append(0)
        new_x.append(name)

输出:

val strings = List("EBAY-SK", "EBAY SK", "EBAY- SK", "EBAY", "EBAYEBAY")

val pattern = """([^.]*?Y).*""".r

strings.foreach(a => pattern.findAllIn(a).matchData foreach {
    m => println(a + " -> " + m.group(1))
})

答案 1 :(得分:1)

您可以使用工作模式,即替换-或\ s(空格)及其后的所有内容:

val finalString1 = string1.replaceAll("[-\\s].*", "")
val finalString2 = string2.replaceAll("[-\\s].*", "")
val finalString3 = string3.replaceAll("[-\\s].*", "")

或者仅使用substring代替replaceAll

val finalString1 = string1.substring(0, 4)
val finalString2 = string2.substring(0, 4)
val finalString3 = string3.substring(0, 4)