0

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#?

2
  • \d Also: do you literally mean a "digit" or a "number"? Commented Mar 4, 2015 at 19:32
  • 1
    You've obviously searched for existing answers and found stuff like stackoverflow.com/questions/4792242/…. Would you mind to clarify what problem you have applying solutions suggested in existing answers? Commented Mar 4, 2015 at 19:42

2 Answers 2

2

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: enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

is there a way to say find the number which is only in the string 'parameter[8]' ?
var regexResult = Regex.Match("parameter[8]", @"^parameter[([0-9]+)]$"); this returns 'paramter[8]' as result. I thought it would return number 8 only.
looks like it doesn't work if it has other words i.e. 'Command parameter[8] data..'. Is there a way if i can get the number from sentence which has word parameter. More like check in this sentence, if it has parameter word and get the number inside the bracket of word parameter?
change the pattern to "parameter[([0-9]+)]"
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.