Scala实现R语言的str_match函数操作

Scala实现R语言的str_match函数

一个超级冷门的操作,我就不行除了我之外还会有人用,用到的老哥请在下面留言(>_<)
R语言的str_match函数不明白的可以在rstudio中输入?str_match
R语言的str_match函数大概的意思就是:
首先找到符合正则匹配规则的字符串(只找第一个),然后后面跟着是每个括号部分里面的对应正则匹配表达式的字符串。

library(stringr)
str_match( "2004-01-20,2018-12-12","(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)")

在这里插入图片描述
scala代码:
依赖:

   def str_match(regex: Regex, waitMatchString: String): List[String] = {
    var groupCount: Integer = 0
    if (waitMatchString != null && waitMatchString.length() != 0) {
      val unanchoredRegex: UnanchoredRegex = regex.unanchored
      val str: String = unanchoredRegex.findFirstIn(waitMatchString).getOrElse("")
      if (str.length != 0) {
        val matchRegex: Regex.Match = unanchoredRegex.findFirstMatchIn(str).getOrElse(null)
        if (matchRegex != null) {
          return List[String](str).++(matchRegex.subgroups)
        }
      }
    }
    groupCount=regex.unanchored.pattern.matcher("").groupCount()
    val resListBuffer: ListBuffer[String] = ListBuffer[String]()
    for (i <- 0 to groupCount){
       resListBuffer.+=(null)
    }
    resListBuffer.toList
  }
  
  def main(args: Array[String]): Unit = {
    val regex: Regex = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
    val str: String = "2004-01-20,2018-12-12"
    val strings: List[String] = str_match(regex, str)
    println(strings)
  }

结果:
在这里插入图片描述
差不多就长这个样子了。
如有疑问请在下面留言,估计没有多少人需要使用这个操作。。。。

发布了56 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/OldDirverHelpMe/article/details/103778984