Regex正则表达式之Shared、NextMatch、IsMatch. (二)
原文地址:http://www.dotnetperls.com/regex-match-vbnet Shared. A Regex object requires time to be created. We can instead share Regex objects,with the shared keyword. A shared Regex object is faster than shared Regex Functions. 共享方法。 一个正则表达式对象需要时间去创造。我们可以用Shared关键字分享regex对象。共享Regex对象的速度比共享的正则表达式方法的速度快。 Therefore: 因此:
功能: Match方法变为一个正则表达式实例化后的一个方法。这个程序与以前的程序相同。 下面是代码: 例四:Shared. 方法 VB.NET program that uses Match on Regex field
Imports System.Text.RegularExpressions
Module Module1
''' <summary> ''' Member field regular expression. ''' </summary> Private _reg As Regex = New Regex("content/([A-Za-z0-9-]+).aspx$",_ RegexOptions.IgnoreCase)
Sub Main() ' The input string. Dim value As String = "/content/alternate-1.aspx"
' Invoke the Match method. ' ... Use the regex field. Dim m As Match = _reg.Match(value)
' If successful,write the group. If (m.Success) Then Dim key As String = m.Groups(1).Value Console.WriteLine(key) End If End Sub
End Module
Output
alternate-1 就是把原来的 Regex.Match方法改为new一个Regex_reg As Regex = New Regex("content/([A-Za-z0-9-]+).aspx$",_ RegexOptions.IgnoreCase)
The Match() Function returns the first match only. But we can call NextMatch() on that returned Match object. This is a match that is found in the text,further on. Match,NextMatch.方法。 Match方法只会返回第一个匹配值,但我们可以使用NextMatch方法在第一个匹配的返回值中再次匹配。这是一个进一步在文本中找到的匹配项的方法。
Tip: 提示: 下面是代码: 例五:NextMatch VB.NET program that uses Match,NextMatch
Imports System.Text.RegularExpressions
Module Module1
Sub Main() ' Get first match. Dim match As Match = Regex.Match("4 and 5","d")
If match.Success Then Console.WriteLine(match.Value) End If
' Get next match. match = match.NextMatch()
If match.Success Then Console.WriteLine(match.Value) End If End Sub
End Module
Output
4 5 先匹配到4,再匹配到5
IsMatch. This returns true if a String matches the regular expression. We get a Boolean that tells us whether a pattern matches. If no other results are needed,IsMatch is useful. 表示是否匹配的布尔值 如果正则表达式与字符串相匹配则返回true.我们用一个布尔值判断标识符是否匹配。如果没有其他需要的结果,IsMatch 就是有用的。
在这里 下面是代码: 例六:IsMatch. VB.NET program that uses Regex.IsMatch function
Imports System.Text.RegularExpressions
Module Module1 Function IsValid(ByRef value As String) As Boolean Return Regex.IsMatch(value,"^[a-zA-Z0-9]*$") End Function
Sub Main() Console.WriteLine(IsValid("dotnetperls0123")) Console.WriteLine(IsValid("DotNetPerls")) Console.WriteLine(IsValid(":-)")) End Sub End Module
Output
True True False [a-zA-Z0-9]意思是范围包括小写字母a至z;大写字母A至Z;数字0至9 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |