Reputation: 323
I'm using this code to count how many group of a regex pattern contain.
Dim GroupCount As Integer = Regex.Match(input, pattern).Groups.Count
It returns success when the pattern matches the input:
Dim GroupCount As Integer = Regex.Match(" something ", "( )something( )").Groups.Count
But it's always returns 1 if the pattern doesn't match.
Dim GroupCount As Integer = Regex.Match("ABC", "( )something( )").Groups.Count
What I need is a function to count number of groups in a pattern in any case.
Upvotes: 3
Views: 2054
Reputation: 1045
If I am getting you correctly then you need to count instances of ( ) in any word.Well If I am correct then this should help you;
Dim s As String = "( )yourstring()somevalue( )getit()"
'A sample string.
Dim rgx As New Regex("(?<BraceGroup>\([ ]*\))", RegexOptions.Singleline)
'Regex pattern to match '( )' or '()'.
Dim matches As MatchCollection = rgx.Matches(s)
'Get all matches.
Dim count As Integer = matches.Count
'Number of matches.
Console.WriteLine(String.Format("Total '() captures' found : {0}", count))
Ideone demo here.
Upvotes: 0
Reputation: 44259
How about Regex.GetGroupNumbers()
?
Dim pattern As New Regex("( )something( )")
Dim groupCount As Integer = pattern.GetGroupNumbers().Length
By obtaining the result from a Regex
object, it's independent of any particular match, which is just what you want.
You might want to subtract 1
from the result, because the entire string is also a group (at index 0
), depending on what you are looking for.
Upvotes: 2
Reputation: 22457
Return Value Type: System.Text.RegularExpressions.Match An object that contains information about the match.
You need to test for GroupCount.Success.
Upvotes: -1