正则表达式学习
好消息:本人博客已开通,更多博客请进 http://swplzj.github.io 项目中经常使用到一些校验,比如有效手机号,身份证号码,邮箱,银行卡号码…假如说都是简单的使用位数来做校验,容易造成特殊字符输入乱码,还有可能在数据库中写入脏数据,所以使用正则表达式来进行校验匹配是很有必要的,当然,我们学习它就要知道它有哪些作用,正则表达式的用途基本有以下三种:
学习正则表达式的最好方法是从例子开始,理解例子之后再自己对例子进行修改。下面开始学习之旅: 语法
后向引用捕获(exp): 匹配exp,并捕获文本到自动命名的组里 (?exp): 匹配exp,并捕获文本到名称为name的组里,也可以写成(?’name’exp) (?:exp): 匹配exp,不捕获匹配的文本,也不给此分组分配组号 零宽断言(?=exp): 匹配exp前面的位置 (?<=exp): 匹配exp后面的位置 (?!exp): 匹配后面跟的不是exp的位置 注释(?#comment): 这种类型的分组不对正则表达式的处理产生任何影响,用于提供注释让人阅读 实例从下面文本中查询出以 The Tasmanian tiger,also known as the Thylacine,has been announced extinct many years ago. Now many geneticists assert that they are capable of recreating a [sid=13_1] from DNA extracted from its bone specimen. nnTasmanian tigers belong to marsupials that have a [sid=13_2] in common. They looked like big dogs with over 15 dark stripes on the body. When chasing their preys,these animals primarily depended on [sid=13_3] to prevail. Their stomach could inflate so they could eat large amount of food each time to [sid=13_4] a period lack of food. 我们发现要查询的内容是以 {% img center /2015_08_14_regular_express_id1.png /%} 再增加点难度,要检索出 解答
{% img center /2015_08_14_regular_express_id2.png /%}
{% img center /2015_08_14_regular_express_id3.png /%} iOS中应用我们在开发iOS项目过程中,使用到正则表达式的主要场景有两种: 第一 在应用中用户输入数据时,做正则匹配校验,这类比较常见,这里就不做详述,但是给出一个比较好的建议,就是把需要校验的项,单独创建一个 XML 文件,然后再自定义标签,属性,来进行统一存放项目中所有校验项,如下: <?xml version="1.0" encoding="utf-8"?>
<rules>
<rule type="mobile" pattern="^1d{10}$" tip="请输入正确的手机号" />
</rules>
上面是简单校验手机号码位数的正则表达式,这样做的好处:方便维护管理;代码更为规范。 第二 在使用
使用场景已经描述完了,但是怎么样实现呢,下面直接上代码: 加载本地 CSS NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
initWithPattern:@"(?i)<s*links*href="[^"]+.css""
options:NSRegularExpressionCaseInsensitive
error:nil];
NSArray *matches = [regularexpression matchesInString:htmlContent options:0 range:NSMakeRange(0,[htmlContent length])];
NSString *content = htmlContent;
NSString *replaceStr = [NSString stringWithFormat:@"<link href="%@"",cssFilePath];
for (NSTextCheckingResult *match in matches){
NSRange matchRange = [match range];
content=[regularexpression stringByReplacingMatchesInString:content options:0 range:matchRange withTemplate:replaceStr];
}
获取图片资源 NSMutableArray *imageIds = [NSMutableArray array];
NSString *str = @"(?i)<divs*classs*=s*"[^"]*img">s*<imgs*[^>]*id=s*"[^>]*>";
NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
initWithPattern:str
options:NSRegularExpressionCaseInsensitive
error:nil];
NSArray *matches = [regularexpression matchesInString:htmlContent
options:0
range:NSMakeRange(0,[htmlContent length])];
对图片进行操作 NSString *str = @"(?i)<divs*class="[^"]*img">s*<imgs*[^>]*id=s*""; str = [str stringByAppendingString:imageInfo.image_id]; str = [str stringByAppendingString:@""s*src=s*"[^"]*"[^>]*>"]; NSString *replacejs = [NSString stringWithFormat:@"<div class="img" id="%@" onclick="location.href='picid'+this.id" style="background-color:#999999;width:%fpx;height:%fpx;" />",imageInfo.image_id,width,height];
replacejs = [replacejs stringByAppendingString:[NSString stringWithFormat:@"<img src="%@" width="%fpx" height="%fpx"/>",imagePath,0.0]];
replacejs = [replacejs stringByAppendingString:[NSString stringWithFormat:@"<img src="%@" width="180px" height="36px" style="margin-left:%fpx;margin-top:%fpx"/>",logoImagePath,(width / 2 - 90),(height/2 - 34)]];
NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
initWithPattern:str
options:NSRegularExpressionCaseInsensitive
error:nil];
NSArray *matches = [regularexpression matchesInString:content options:0 range:NSMakeRange(0,[content length])];
for (NSTextCheckingResult *match in matches){
NSRange matchRange = [match range];
content=[regularexpression stringByReplacingMatchesInString:content options:0 range:matchRange withTemplate:replacejs];
}
放大缩小页面中的文本 NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'",textFontScale]; [_webView stringByEvaluatingJavaScriptFromString:jsString];
扩展 - 在本地HTML中加入JS NSString *js = @"<script language="javascript" type="text/javascript">";
//替换css文件
js = [js stringByAppendingString:@"function replacejscssfile(oldfilename,newfilename,filetype){ var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none"; var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none"; var allsuspects=document.getElementsByTagName(targetelement); for (var i=allsuspects.length; i>=0; i--){ if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){ var newelement=createjscssfile(newfilename,filetype); allsuspects[i].parentNode.replaceChild(newelement,allsuspects[i]);} } return "sdasds";}"];
js = [js stringByAppendingString:@"</script></head>"];
NSString *content = [htmlContent stringByReplacingOccurrencesOfString:@"</head>" withString:js];
常用正则表达式网址(URL): [a-zA-z]+://[^s]* IP地址(IP Address): ((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?) 电子邮件(Email): w+([-+.]w+)@w+([-.]w+).w+([-.]w+)* QQ号码: [1-9]d{4,} HTML标记(包含内容或自闭合): <(.)(.)>.</1>|<(.) /> 密码(由数字/大写字母/小写字母/标点符号组成,四种都必有,8位以上): (?=^.{8,}
日期(年-月-日): (d{4}|d{2})-((1[0-2])|(0?[1-9]))-(([12][0-9])|(3[01])|(0?[1-9])) 日期(月/日/年): ((1[0-2])|(0?[1-9]))/(([12][0-9])|(3[01])|(0?[1-9]))/(d{4}|d{2}) 时间(小时:分钟,24小时制): ((1|0?)[0-9]|2[0-3]):([0-5][0-9]) 汉字(字符): [u4e00-u9fa5] 中文及全角标点符号(字符): [u3000-u301eufe10-ufe19ufe30-ufe44ufe50-ufe6buff01-uffee] 中国大陆固定电话号码: (d{4}-|d{3}-)?(d{8}|d{7}) 中国大陆手机号码: 1d{10} 中国大陆邮政编码: [1-9]d{5} 中国大陆身份证号(15位或18位): d{15}(dd[0-9xX])? 非负整数(正整数或零): d+ 正整数: [0-9][1-9][0-9] 负整数: -[0-9][1-9][0-9] 整数: -?d+ 小数: (-?d+)(.d+)? 不包含abc的单词: b((?!abc)w)+b 后记整理这篇博文的过程中,当然涉及到的知识不仅仅是正则表达式,还有后面通过 webview 和 JavaScript 进行交互,这是另一方面的知识了,就不在这里介绍了。马上七夕情人节了,大家快乐。就写到这里啦,还没有准备礼物,赶紧准备,不然… 参考博文:正则表达式30分钟入门教程 好消息:本人博客已开通,更多博客请进 http://swplzj.github.io (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |