scala--regular expression-★★

Regular expression-★★

Regex class

  • The Regex class is provided in scala to define regular expressions
    • To construct a Regex object, you can use the new Regex method, or directly use the r method of the String class.
    • val regex1 = new Regex("""Regular expression""")
    • val regex2 = """Regular expression""".r //It is recommended to use three double quotation marks to represent the regular expression, otherwise you have to escape the backslash in the regular expression
  • findAllMatchIn method
    • Use the findAllMatchIn method to get all the strings matched by the regular
  • The regularity itself is a very complex content, there are many rules, here you can understand
  • Learn the API, not how to write regular expressions
package cn.hanjiaxiaozhi.regex
​
import scala.util.matching.Regex
​
/**
 * Author hanjiaxiaozhi
 * Date 2020/7/19 9:32
 * Desc 演示Scala的正则表达式语法
 */
object RegexDemo {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //定义一个用来匹配邮箱的正则表达式
    //val regex: Regex = new Regex(".+@.+\..+")//格式一
    //val regex: Regex = """.+@.+\..+""".r //格式二
    val regex: Regex = """^\w+@[a-z0-9]+\.[a-z]+$""".r //格式二//准备一些带验证的邮箱
    val emails = List("[email protected]", "[email protected]", "[email protected]", "1234aa.com")//一个个的校验,如1234aa.com
    val matches: Iterator[Regex.Match] = regex.findAllMatchIn("1234aa.com")
    println(matches)//empty iterator
    println(matches.size)//0//一次性校验多个,如过滤出emails中的非法邮箱,也就是如果非法则返回true则会被过滤出来
    val invalidEmails: List[String] = emails.filter(email => {
    
    
      if (regex.findAllMatchIn(email).size < 1) {
    
     //非法
        true
      } else {
    
    
        false
      }
    })
    println(invalidEmails)//List(1234aa.com)
  }
}

Guess you like

Origin blog.csdn.net/qq_46893497/article/details/114044173