根据正则表达式过滤scala中的列表
Filter the list in scala based on the regular expression
我在 Scala 中有一个列表如下。
val inputList :List[String] = List("Manager","VP", "12/09/2011","Access","10/11/2021 1:51 PM","Agent","Customer Contact date 07/23/2011", "Profile")
inputList: List[String] = List(Manager, VP, 12/09/2011, Access, 10/11/2021 1:51 PM, Agent, Customer Contact date 07/23/2011, Profile)
现在我想忽略仅以日期开头的列表元素。所以当我过滤并打印列表时,我应该得到如下所示。
Manager
VP
Access
Agent
Customer Contact date 07/23/2011
Profile
我试过了
scala>var finalList = List[String]()
scala> finalList = inputList.filterNot(r => r.startsWith("[0-9]{1,2}[/][0-9]{1,2}[/][0-9]{4}"))
finalList: List[String] = List(Manager, VP, 12/09/2011, Access, 10/11/2021 1:51 PM, Agent, Customer Contact date 07/23/2011, Profile)
我仍然看到以日期开头的元素。我尝试了如下不同的正则表达式格式,但仍然看到它没有忽略它们。我使用的正则表达式有问题吗?我尝试了 scala> finalList = inputList.filterNot(r => r.startsWith("\d{1,2}[/]\d{1,2}[/]\d{4}")
并且仍然看到它没有删除以日期开头的列表元素。我能得到一些建议吗...
谢谢
使用 startsWith 不需要正则表达式。您可以使用 findFirstIn
然后 filterNot 非空值。
您可能会使用
val inputList :List[String] = List("Manager","VP", "12/09/2011","Access","10/11/2021 1:51 PM","Agent","Customer Contact date 07/23/2011", "Profile")
val rgx = "^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}".r
val finalList: List[String] = inputList.filterNot(s =>
rgx.findFirstIn(s)
.nonEmpty
)
finalList
输出
res0: List[String] = List(Manager, VP, Access, Agent, Customer Contact date 07/23/2011, Profile)
或者使用带有 isEmpty 的过滤器
val finalList: List[String] = inputList.filter(s => rgx.findFirstIn(s).isEmpty)
我在 Scala 中有一个列表如下。
val inputList :List[String] = List("Manager","VP", "12/09/2011","Access","10/11/2021 1:51 PM","Agent","Customer Contact date 07/23/2011", "Profile")
inputList: List[String] = List(Manager, VP, 12/09/2011, Access, 10/11/2021 1:51 PM, Agent, Customer Contact date 07/23/2011, Profile)
现在我想忽略仅以日期开头的列表元素。所以当我过滤并打印列表时,我应该得到如下所示。
Manager
VP
Access
Agent
Customer Contact date 07/23/2011
Profile
我试过了
scala>var finalList = List[String]()
scala> finalList = inputList.filterNot(r => r.startsWith("[0-9]{1,2}[/][0-9]{1,2}[/][0-9]{4}"))
finalList: List[String] = List(Manager, VP, 12/09/2011, Access, 10/11/2021 1:51 PM, Agent, Customer Contact date 07/23/2011, Profile)
我仍然看到以日期开头的元素。我尝试了如下不同的正则表达式格式,但仍然看到它没有忽略它们。我使用的正则表达式有问题吗?我尝试了 scala> finalList = inputList.filterNot(r => r.startsWith("\d{1,2}[/]\d{1,2}[/]\d{4}")
并且仍然看到它没有删除以日期开头的列表元素。我能得到一些建议吗...
谢谢
使用 startsWith 不需要正则表达式。您可以使用 findFirstIn
然后 filterNot 非空值。
您可能会使用
val inputList :List[String] = List("Manager","VP", "12/09/2011","Access","10/11/2021 1:51 PM","Agent","Customer Contact date 07/23/2011", "Profile")
val rgx = "^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}".r
val finalList: List[String] = inputList.filterNot(s =>
rgx.findFirstIn(s)
.nonEmpty
)
finalList
输出
res0: List[String] = List(Manager, VP, Access, Agent, Customer Contact date 07/23/2011, Profile)
或者使用带有 isEmpty 的过滤器
val finalList: List[String] = inputList.filter(s => rgx.findFirstIn(s).isEmpty)