简体   繁体   中英

How can I extract a number out of a string using regex?

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:

errors

Seems like your question is actually 2 questions.

1. 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\""

2. How can I extract a number out of a string using Regex?

Do you just want to get a number within any type of string no matter the format through Regex? If that's the case all you'll have to do is:

var result = int.Parse(new Regex(@"\d+").Match("/ \"},{\"text\":\"36\"").Value); // Outputs 36 as an integer

However I'd strongly recommend not using a Regex for simple tasks like this, since they're very performance heavy. Here's a much better way to do that: https://stackoverflow.com/a/15669520/9988162

If your format is consistent, please update your question so that we can build a format for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM