.+),然后使用相应的解析器进行解析,得到两个分组user组和host组,user组里存储用户名wangyi,host组里存放服务器名163.com,而用传统的方法是很难实现这种分解的。
由此可见,作为一种字符串处理方式,正则表达式的灵活与强大确实是传统字符串处理方式无法相比的。
vb.net 中的正则表达式处理类
在vb.net中使用正则表达式必须先引入命名空间system.text.regularexpressions,该命名空间包含一下七个类:regex、match、matchcollection、groupcollection、capturecollection、group、capture。
regex类表示不可变(只读)正则表达式类,设置待匹配字符串的模式。match类表示正则表达式匹配操作的结果。matchcollection 类表示成功的非重叠匹配的序列,即匹配后得到的字符串集合。在正则表达式中应用最多的就是这三个类。
使用正则表达式类的通用方法是:
首先生成一个regex类的实例,并在传入参数中输入正则表达式的模式,然后使用regex类的相应方法,如ismatch(判断是否匹配)、match(返回匹配得到的字符串)等等。
牛刀小试
代码
imports system.text.regularexpressions
public class frmtest
'定义存放正则表达式的常量
private const c_regular_card = "^\d{0,12}$" '卡号的输入正则表达式(长度12以内的数字)
private const c_regular_length = "^.{0,10}$" '输入字符长度正则表达式(长度10以内字符)
private const c_regular_chinese = "^[\u4e00-\u9fa5]{0,}$" '只能输入汉字的正则表达式
private sub btncheck_click(byval sender as system.object, byval e as system.eventargs) handles btncheck.click
if txtregular.text.trim.length = 0 then '如果字符为空,退出过程
msgbox("请输入字符!")
exit sub
end if
dim strpattern as string = string.empty '正则表达式变量
dim strcheckedtext as string = string.empty '选择的检查项
'判断赋值
if checkcard.checked then
strpattern = c_regular_card '赋值正则表达式
strcheckedtext = checkcard.text '赋值检查项
elseif checklength.checked then
strpattern = c_regular_length
strcheckedtext = checklength.text
elseif checkchinese.checked then
strpattern = c_regular_chinese
strcheckedtext = checkchinese.text
end if
'调用判断函数,传入参数,并给出相应提示
if funcheckregular(strpattern, txtregular.text) = true then
msgbox(">---符合规范!", msgboxstyle.information, me.text)
else
msgbox(">---不符规范!", msgboxstyle.exclamation, me.text)
end if
end sub
'''
''' 判断输入字符串是否匹配正则表达式
'''
''' 正则表达式变量
''' 输入字符串变量
''' 返回布尔值,匹配返回true,否则返回false
''' 2014-07-17 19:54:25 牛迁迁
public function funcheckregular(byval strpattern as string, textreg as string) as boolean
return regex.ismatch(textreg, strpattern)
end function
private sub btnclear_click_1(sender as object, e as eventargs) handles btnclear.click
txtregular.clear()
end sub
end class ’注:这只是一个小demo,没有采用分层写法。
显示:(请看效果,其实它会动的,可惜csdn竟然不支持gif图!点击连接查看
https://m18831658786.blog.163.com/prevphdownload.do?host=m18831658786&albumid=269674986&photoid=8926571224)
总结
正则表达式的特点是:
1.灵活性、逻辑性和功能性非常的强;
2.可以迅速地用极简单的方式达到字符串的复杂控制效果
3.对于刚接触的人(我)来说,比较晦涩难懂。
正则表达式博大精深,能够做到许多你想不到的事情,赶紧试试吧!
更多了解,请点击:https://baike.baidu.com/view/94238.htm?fr=aladdin