当前位置:网站首页>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
无
边栏推荐
- 目标检测技术研究现状及发展趋势
- How many way of calling a function?
- Storage engine written by golang, based on b+ tree, mmap
- Cisco ike2 IPSec配置
- Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
- FinClip最易用的智能电视小程序
- Embedded systems: overview
- 《数字经济全景白皮书》金融数字用户篇 重磅发布!
- Network basic learning series four (network layer, data link layer and some other important protocols or technologies)
- Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
猜你喜欢

Live Preview | Build Business Intelligence, Quickly Embrace Financial Digital Transformation

《数字经济全景白皮书》金融数字用户篇 重磅发布!

重发布实验报告

Walk the Maze BFS

What is Adobe?

Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!

node连接mysql数据库报错:Client does not support authentication protocol requested by server

BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes

for loop exercises

牛客2022 暑期多校3 H Hacker(SAM + 线段树查询区间内部最大子段和)
随机推荐
The sword refers to the offer question 22 - the Kth node from the bottom in the linked list
PowerMockup 4.3.4::::Crack
Why do we need callbacks
LabVIEW code generation error 61056
node连接mysql数据库报错:Client does not support authentication protocol requested by server
【论文阅读】TRO 2021: Fail-Safe Motion Planning for Online Verification of Autonomous Vehicles Using Conve
UVa 437 - The Tower of Babylon(白书)
BMN: Boundary-Matching Network for Temporal Action Proposal Generation Reading Notes
Embedded Systems: Clocks
HDU 5655 CA Loves Stick
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
为什么我们需要回调
Testng监听器
静态文件快速建站
Pytest learn-setup/teardown
藏宝计划TreasureProject(TPC)系统模式开发技术原理
for loop exercises
UVa 10003 - Cutting Sticks(白书,区间DP)
AOSP CameraLatencyHistogram的原理与使用
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication