文章目录
- 背景
- 方法总览
- isMatch 自定义正则基本用法
- 用 try/catch 保护正则错误
- 常用正则写法速查
- 正则字符串中的转义问题
- 完整的自定义正则验证示例
- 写在最后
背景
近期发现一款很有意思的HarmonyOS 三方库, 地址 @pura/harmony-utils(V1.4.0) , 作者是"桃花镇童长老", 我这里也是直接通过该作者公布的源码进行案例编写进行,写了到目前写了一部分demo ,感觉确实很有帮助,这里呢也是开始写一个系列的演示demo 供大家参考。如有帮助可以在OpenHarmony中进行下载安装进行使用哦
案例demo导航展示
↓↓↓↓↓↓接下来言归正传 ↓↓↓↓
前两篇讲了RegexUtil的内置验证方法。但内置方法毕竟有限,遇到特殊的业务格式怎么办?比如你要验证用户自定义的密码强度规则、特定格式的单号、或者特殊的编号格式。
isMatch支持传入自定义正则字符串,这篇就讲怎么用。
方法总览
isMatch 自定义正则基本用法
isMatch(str, pattern)的第二个参数除了内置常量,还可以传正则字符串:
// Demo 中的自定义正则区域this.SectionTitle('isMatch() 自定义正则')TextInput({text:this.inputCustom,placeholder:'测试字符串'}).width('100%').height(38).fontSize(13).onChange(v=>{this.inputCustom=v;})TextInput({text:this.inputCustomRegex,placeholder:'正则字符串 e.g. ^[a-z]+$'}).width('100%').height(38).fontSize(13).onChange(v=>{this.inputCustomRegex=v;})this.Btn('isMatch(输入, 自定义正则)','#884EA0',()=>{try{constr=RegexUtil.isMatch(this.inputCustom,this.inputCustomRegex);this.addLog(`isMatch("${this.inputCustom}", "${this.inputCustomRegex}") →${r}`);}catch(e){this.addLog(`正则错误:${e}`);}})Demo 里设计了两个输入框:一个输入测试字符串,一个输入正则表达式。点击按钮实时验证。
用 try/catch 保护正则错误
注意 Demo 代码里有try/catch。这是因为如果用户输入了非法的正则表达式(比如[未闭合),isMatch会抛出异常。
try{constr=RegexUtil.isMatch(this.inputCustom,this.inputCustomRegex);this.addLog(`isMatch("${this.inputCustom}", "${this.inputCustomRegex}") →${r}`);}catch(e){this.addLog(`正则错误:${e}`);}在生产代码里,如果正则是固定的(你写死的),不需要try/catch;如果正则是用户输入的,必须加try/catch保护。
常用正则写法速查
正则表达式的语法可能对初学者来说有点难,这里给出几个实际业务中常用的例子:
密码强度验证(至少8位,包含字母和数字):
constpasswordRegex='^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$';RegexUtil.isMatch('Abc12345',passwordRegex)// → trueRegexUtil.isMatch('12345678',passwordRegex)// → false(没有字母)RegexUtil.isMatch('abcdefgh',passwordRegex)// → false(没有数字)纯小写字母(Demo 默认正则就是这个):
RegexUtil.isMatch('abc','^[a-z]+$')// → trueRegexUtil.isMatch('abc123','^[a-z]+$')// → false(包含数字)RegexUtil.isMatch('Abc','^[a-z]+$')// → false(包含大写)指定长度的数字验证码(6位):
RegexUtil.isMatch('123456','^\\d{6}$')// → trueRegexUtil.isMatch('12345','^\\d{6}$')// → false(5位)RegexUtil.isMatch('1234567','^\\d{6}$')// → false(7位)中文姓名(2-4个汉字):
RegexUtil.isMatch('张三','^[\\u4e00-\\u9fa5]{2,4}$')// → trueRegexUtil.isMatch('A张三','^[\\u4e00-\\u9fa5]{2,4}$')// → false(包含英文)RegexUtil.isMatch('张','^[\\u4e00-\\u9fa5]{2,4}$')// → false(只有1个字)订单号格式(字母+年月日+6位数字,如 ORD20240101000001):
RegexUtil.isMatch('ORD20240101000001','^ORD\\d{14}$')// → true正则字符串中的转义问题
在 ArkTS/TypeScript 字符串里写正则,需要注意转义符\要写两个:
| 正则语法 | 字符串写法 | 含义 |
|---|---|---|
\d | "\\d" | 匹配数字 |
\w | "\\w" | 匹配字母、数字、下划线 |
\s | "\\s" | 匹配空白字符 |
\u4e00 | "\\u4e00" | Unicode 码点(中文开始) |
. | "." | 匹配任意字符(在字符类外) |
\. | "\\." | 匹配字面上的点 |
这是初学者最容易出错的地方。如果写"\d"而不是"\\d",在 TypeScript 里\d会被当成普通字符串(因为\d不是有效的转义序列),导致正则不符合预期。
完整的自定义正则验证示例
importrouterfrom'@ohos.router';import{RegexUtil}from'../Utils/RegexUtil';interfaceLogItem{time:string;text:string;}@Entry@Componentstruct RegexUtilDemoPage{@Statelogs:LogItem[]=[];@StateinputCustom:string='abc123';@StateinputCustomRegex:string='^[a-z]+$';privateaddLog(text:string){constd=newDate();consttime=`${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}:${d.getSeconds().toString().padStart(2,'0')}`;constnewItem:LogItem={time,text};this.logs=([newItem]asLogItem[]).concat(this.logs).slice(0,60);}build(){Column(){// 自定义正则输入区Text('自定义正则验证').fontSize(13).fontColor('#888').fontWeight(FontWeight.Bold).padding({left:4,top:8,bottom:2}).width('100%')TextInput({text:this.inputCustom,placeholder:'测试字符串'}).width('100%').height(38).fontSize(13).onChange(v=>{this.inputCustom=v;})TextInput({text:this.inputCustomRegex,placeholder:'正则字符串 e.g. ^[a-z]+$'}).width('100%').height(38).fontSize(13).onChange(v=>{this.inputCustomRegex=v;})Button('isMatch(输入, 自定义正则)').width('100%').height(40).fontSize(14).fontColor('#fff').backgroundColor('#884EA0').borderRadius(8).onClick(()=>{try{constr=RegexUtil.isMatch(this.inputCustom,this.inputCustomRegex);this.addLog(`isMatch("${this.inputCustom}", "${this.inputCustomRegex}") →${r}`);}catch(e){this.addLog(`正则错误:${e}`);}})}.padding(16)}}写在最后
自定义正则加上内置常量,RegexUtil几乎能覆盖所有验证场景。
学习正则表达式有点门槛,但常用的几个模式(\d数字、\w字母数字、{n,m}长度范围、^...$完整匹配)搞懂了就能应对大多数业务需求。
遇到复杂的正则,可以在 regex101.com 上调试好再放进代码里。