Reputation: 9617
I am trying to capture number from my error message i.e something like this
Command parameter[8] '' data value could not be converted for reasons
Does anyone know how to get the number i.e. 8 from the following string using regular expression in c#?
Upvotes: 0
Views: 137
Reputation: 31721
If the number is going to be the only number in the string then simply the pattern by just searching for a number:
\d+
- Which says match on a number +
one or more.
Upvotes: 0
Reputation: 1944
Use the following pattern:
\[([0-9]+)\]
Demo: https://regex101.com/r/mE0rX2/2
Edit: If you want to restrict matches to strings in the form of "parameter[digits_here]
", use the following pattern:
^parameter\[([0-9]+)\]$
Demo: https://regex101.com/r/xE3tY4/1
Edit1: Code snippet in VB.net. Hopefully, you can translate that to C#
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String : str = "parameter[8]"
Dim regex As New Regex("^parameter\[([0-9]+)\]$")
For Each m In regex.Matches(str)
MsgBox(m.groups(1).ToString)
Next
End Sub
End Module
output:
Upvotes: 2