I have this string out of a very long line it can be longer but I decided to take this part of the line :
/ "},{"text":"36"
and I want to get the number from the string. or from the whole line to get this number specific after the char / and the text : "36" the line is too long to post here.
I tried this :
private void GetNumber()
{
string subjectstring = "/ "},{"text":"36"";
string resultString = Regex.Match(subjectstring, @"\d ").Value;
}
The problem is I'm getting some errors on the right side of the line :
string subjectstring = "/ "},{"text":"36"";
screenshot of the errors I'm getting :
CodePudding user response:
Seems like your question is actually 2 questions.
- Why am I getting an error when initializing string with
"/ "},{"text":"36""value
That's because the quotation mark signifies the beginning / ending of a string sequence. Since your string itself has multiple quotation marks, the compiler thinks you want to end the string and start it later again and some characters in between might just randomly circle around in your program which causes the compiler error.
To fix this use \ in front of each quotation mark that should be part of the value to tell the compiler that you're not trying to end the string yet. In your example it should look like this: "/ \"},{\"text\":\"36\""
- How can I extract a number out of a string using Regex?
For your specific format of"runs":[{"text":"NUMBER"} it's actually really simple since it's always the same:
var format = new Regex("\"(\\d )\"");
var input = "\"runs\":[{\"text\":\"36\""; // "runs":[{"text":"36"}
int result = int.Parse(format.Match(input).Groups[1].Value); // Outputs 36
