RegEx to match text and enclosed curly braces
I need to loop through all matches, for example the following line:
<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>
I want to capture values ββin {} including them, so I want {ProductRowID} and {ProductName}
Here is my code:
Dim r As Regex = New Regex("{\w*}", RegexOptions.IgnoreCase)
Dim m As Match = r.Match("<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>")
Is my RegEx pattern correct? How do I loop through the values? I feel like it should be very easy, but I was stumped this morning!
source to share
There is a small detail missing in your template:
\{\w*?\}
Moving braces must be shielded, and you want to unwanted star, or your first (and only) match will be as follows: "{ProductRowID}'>{ProductName}"
.
Dim r As Regex = New Regex("\{\w*?\}")
Dim input As String = "<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>"
Dim mc As MatchCollection = Regex.Matches(input, r)
For Each m As Match In mc
MsgBox.Show(m.ToString())
Next m
RegexOptions.IgnoreCase
not required because this particular regex is case insensitive.
source to share
You can simply group your matches using a regex as shown below:
<a href='/Product/Show/(.+)'\>(.+)</a>
This way you have $ 1 and $ 2 corresponding to the values ββyou want.
You also give the names of your matches so that they are not anonymous / position oriented for searches:
<a href='/Product/Show/(?<rowid>.+)'\>(?<name>.+)</a>
source to share
Change the RegEx template to \{\w*\}
then it will match as you expect.
You can test it with the RegEx online tester .
source to share