String 当某个单词出现在字符串中时,Scala获取最后一个单词

String 当某个单词出现在字符串中时,Scala获取最后一个单词,string,scala,String,Scala,我有这个清单。我如何提取[鹰嘴豆、甘薯] 我需要搜索插件,并得到最后一个字的网址 "https://apple.com/adm/context/events/AllEvents", "https://apple.com/adm/plugins/common/SweetPotatoes" "https://apple.com/adm/plugins/common/Cheakpeas" 我的尝试是这样的。我想要更优雅的 var lst=

我有这个清单。我如何提取[鹰嘴豆、甘薯]

我需要搜索插件,并得到最后一个字的网址

"https://apple.com/adm/context/events/AllEvents",
"https://apple.com/adm/plugins/common/SweetPotatoes"
"https://apple.com/adm/plugins/common/Cheakpeas"
我的尝试是这样的。我想要更优雅的

var lst= List[String]()
for (url <- allUrls) {
  if (a.contains("plugins")) {
    lst ::= a.split("/").last.replace(""""""","")
  }
}
print(lst)
var lst=List[String]()

对于(url您希望从末尾开始运行一个循环,构建一个字符串,并在到达“/”时停止

考虑一个变量

url = s://apple.com/adm/plugins/common/SweetPotatoes"
Psuedo代码:

(假设您已经执行了.contains(插件)检查)


假设您在列表中有原始输入,您可以

import java.net.URI
import java.nio.file.Paths

val urls: List[String] = List("https://apple.com/adm/plugins/common/Cheakpeas",
  "https://apple.com/adm/context/events/AllEvents",
  "https://apple.com/adm/plugins/common/SweetPotatoes")

val pluginList: Seq[String] =
  urls.filter(u => u.contains("plugins")).
    map(u => Paths.get(new URI(u).getPath).getFileName.toString)
试试正则表达式模式

val pluginsRE = ".*/plugins/.*/([^/]+)".r
allUrls.collect{case pluginsRE(s) => s}
//res0: List[String] = List(SweetPotatoes, Cheakpeas)

在这种情况下,模式需要在“插件”部分和目标字符串之间有一个间隙。可以根据需要进行调整。

另一个选项是:

allUrls.filter(u => u.contains("plugins")).map(_.split('/').last)
代码在上运行

或:

代码在上运行

allUrls.filter(u => u.contains("plugins")).map(_.split('/').last)
allUrls.collect { case u if u.contains("plugins") => u.split('/').last }