当前位置:网站首页>Scala basics [regular expressions, framework development principles]
Scala basics [regular expressions, framework development principles]
2022-08-03 22:53:00 【hike76】
文章目录
一 正则表达式
1 介绍
Regular expressions are a lot like pattern matching
Pattern matching matches rules:类型,常量,元组,集合,数组,对象,参数
Regular expressions also match rules:String
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等.


2 基本语法
def main(args: Array[String]): Unit = {
//声明规则
val regex = "a".r
//准备数据
val data = "zhangsan"
//Validate data using rules
val maybeString: Option[String] = regex.findFirstIn(data)
if(maybeString.isEmpty){
println("String does not match rule")
}else{
println("字符串匹配规则:" + maybeString.get)
}
3 案例
(1)验证手机号
Determine if a string is a phone number without using regular expressions(部分功能)
def main(args: Array[String]): Unit = {
println(checkTel("xxxxxxxxxxx"))
println(checkTel("11111111111"))
}
def checkTel(tel : String) : Boolean ={
if(tel.size == 11){
var r = true
Breaks.breakable{
for(c <- tel){
try{
c.toString.toInt
}catch {
case e : Exception => {
r = false
Breaks.break()
}
}
}
}
r
}else{
false
}
}
Use regular expressions to determine if a string is a phone number
\\d:Indicates that there is a number in the string
^:表示字符串的开始位置
$:表示字符串的结束位置
^\\d$:The string has only one number from beginning to end
^\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d$:Match eleven numbers
^\d{11}$:数字重复11次
[0-9]:类似于\\d
a|b:a,bOne of the two conditions is satisfied
((13[0-9])| 13开头,后一位为0-9任何数字都可以
(14[5,7,9])| 14开头,后一位为5,7,9都可以
(15[^4])| 15开头,The last digit does not include numbers
(18[0-9])|
(17[0,1,3,5,6,7,8]))
def main(args: Array[String]): Unit = {
// 构建正则表达式
println(isMobileNumber("18801234567"))
println(isMobileNumber("11111111111"))
}
def isMobileNumber(number: String): Boolean ={
val regex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))[0-9]{8}$".r
val length = number.length
regex.findFirstMatchIn(number.slice(length-11,length)) != None
}
(2)Extract email addresses
def main(args: Array[String]): Unit = {
// 构建正则表达式
val r = """([_A-Za-z0-9-]+(?:\.[_A-Za-z0-9-\+]+)*)(@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*(?:\.[A-Za-z]{2,})) ?""".r
println(r.replaceAllIn("[email protected] [email protected]", (m => "*****" + m.group(2))))
}
二 WordCountFramework development rules
1 架构模式
(1)MVC
MVC:Model View Controller,Force the code to be broken down into three components,模型、视图、控制器
模型:Divided into data model and business model
视图:用户看到的界面
控制器:调度器,Scheduling view,The relationship between business and data
针对B/S结构的服务
(2)三层架构
Controller:控制器
Service:逻辑服务,Corresponds to the business model in the model
DAO:Data Acess Object,Corresponds to the data model in the model
Problems are easy to deal with,增强扩展性,降低耦合性
Request access to the controller first,The controller finds the corresponding oneservice,再由service访问DAO,层层递进,依次返回结果
2 代码实现
调用关系: TApplication – TController – TService – TDao
Application – Controller – Service – Dao
Util
(1)Application
package com.hike.bigdata.scala.summer.application
import com.hike.bigdata.scala.summer.common.TApplication
import com.hike.bigdata.scala.summer.controller.WordCountController
object WordCountApplication extends App with TApplication {
execute {
//Pass the user request toController层
val controller = new WordCountController
//获取从ControllerThe result returned by the layer
controller.dispatch()
}
}
(2)Controller
package com.hike.bigdata.scala.summer.controller
import com.hike.bigdata.scala.summer.common.TController
import com.hike.bigdata.scala.summer.service.WordCountService
class WordCountController extends TController {
// private:只在controller层中访问service层
// Controller调度Service层
private val wordCountService = new WordCountService
def dispatch(): Unit = {
//获取servicelayer to get the result,输出到控制台
val wordCount: Map[String, Int] = wordCountService.analysis()
println(wordCount)
}
}
(3)Service
package com.hike.bigdata.scala.summer.service
import com.hike.bigdata.scala.summer.common.TService
import com.hike.bigdata.scala.summer.dao.WordCountDao
class WordCountService extends TService {
//只在service层中访问DAO层
//Service层访问Dao层
private val WordCountDao = new WordCountDao
def analysis() = {
// 从daolayer to get the file content,执行代码逻辑
// 返回结果WordCount
val lines = WordCountDao.readFile("data/word.txt")
val words = lines.flatMap(
line => line.split(" ")
)
val wordGroup = words.groupBy(word => word)
val wordCount = wordGroup.mapValues(
v => v.size
)
wordCount
}
}
(4)Dao
package com.hike.bigdata.scala.summer.dao
import com.hike.bigdata.scala.summer.common.TDao
//Use methods from abstract classes
class WordCountDao extends TDao {
}
(5)Common
Applicationlayer properties
package com.hike.bigdata.scala.summer.common
import com.hike.bigdata.scala.summer.util.EnvCache
//抽取ApplicationGeneric method for layers
trait TApplication {
def execute(op: => Unit): Unit = {
//Send the system configuration to the shared area
EnvCache.put("e:/")
println("开启环境")
//执行代码逻辑
try {
op
} catch {
case e: Exception => e.printStackTrace()
}
println("释放环境")
EnvCache.clear()
}
// def execute(): Unit ={
// //模板方法设计模式,一般以do开头
// println("开启环境")
//
// try{
// doExecute()
// }catch {
// case e: Exception => e.printStackTrace()
// }
// println("释放环境")
// }
// def doExecute():Unit
}
Controllerlayer properties
package com.hike.bigdata.scala.summer.common
//ControllerHow the layer operates,由实现类实现
trait TController {
def dispatch(): Unit
}
servicelayer properties
package com.hike.bigdata.scala.summer.common
//servicelayer execution method,由实现类实现
trait TService {
def analysis(): Any
}
Daolayer properties
package com.hike.bigdata.scala.summer.common
import com.hike.bigdata.scala.summer.util.EnvCache
import scala.io.{
BufferedSource, Source}
trait TDao {
//读取文件,返回文件内容
def readFile(path: String) = {
//EnvCache.getGet the file root directory
val source: BufferedSource = Source.fromFile(EnvCache.get() + path)
val lines = source.getLines().toList
source.close()
lines
}
}
(6)Util
package com.hike.bigdata.scala.summer.util
object EnvCache {
//Carve out a space in the thread,The data in this space can be fetched by any layer
//ThreadLocalDoes not solve thread safety issues,只是共享数据
private val envCache: ThreadLocal[Object] = new ThreadLocal[Object]
def put(data: Object): Unit = {
envCache.set(data)
}
def get() = {
envCache.get()
}
def clear(): Unit = {
envCache.remove()
}
}
(7)Bean
无
边栏推荐
- win10系统下yolov5-V6.1版本的tensorrt部署细节教程及bug修改
- FinClip,助长智能电视更多想象空间
- Embedded systems: overview
- [MySQL Advanced] Creation and Management of Databases and Tables
- Summary bug 】 【 Elipse garbled solution project code in Chinese!
- UVa 10003 - Cutting Sticks (White Book, Interval DP)
- 牛客2022 暑期多校3 H Hacker(SAM + 线段树查询区间内部最大子段和)
- 【RYU】rest_router.py源码解析
- 冰河又一MySQL力作出版(文末送书)!!
- 软测人每个阶段的薪资待遇,快来康康你能拿多少?
猜你喜欢

关于IDO预售系统开发技术讲解丨浅谈IDO预售合约系统开发原理分析
![[N1CTF 2018] eating_cms](/img/09/3599d889d9007eb45c6eab3043f0c4.png)
[N1CTF 2018] eating_cms

Cloud platform construction solutions

电商秒杀系统

noip初赛

Conditional Statements for Shell Programming

encapsulation, package, access modifier, static variable

Binary search tree to solve the fallen leaves problem

2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis

Cisco ike2 IPSec配置
随机推荐
软测人每个阶段的薪资待遇,快来康康你能拿多少?
UVa 437 - The Tower of Babylon (White Book)
工作小计 QT打包
Network basic learning series four (network layer, data link layer and some other important protocols or technologies)
Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
start with connect by implements recursive query
Golang Chapter 1: Getting Started
Internet user account information management regulations come into effect today: must crack down on account trading and gray products
node连接mysql数据库报错:Client does not support authentication protocol requested by server
complete binary tree problem
Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
BMN: Boundary-Matching Network for Temporal Action Proposal Generation阅读笔记
Golang第一章:入门
Cisco ike2 IPSec配置
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
目标检测的国内外研究现状
MiniAPI of .NET6 (14): Cross-domain CORS (Part 1)
Take an example of a web worker
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
Testng listener