Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Numbers from String RegEx

Tags:

c#

regex

I am really struggling with Regular Expressions and can't seem to extract the number from this string

"id":143331539043251,

I've tried with this ... but I'm getting compilation errors

var regex = new Regex(@""id:"\d+,");

Note that the full string contains other numbers I don't want. I want numbers between id: and the ending ,

like image 479
James Jeffery Avatar asked Jun 24 '26 00:06

James Jeffery


2 Answers

Try this code:

var match = Regex.Match(input, @"\""id\"":(?<num>\d+)");
var yourNumber = match.Groups["num"].Value;

Then use extracted number yourNumber as a string or parse it to number type.

like image 145
kyrylomyr Avatar answered Jun 25 '26 13:06

kyrylomyr


If all you need is the digits, just match on that:

[0-9]+

Note that I am not using \d as that would match on any digit (such as Arabic numerals) in the .NET regex engine.


Update, following comments on the question and on this answer - the following regex will match the pattern and place the matched numbers in a capturing group:

@"""id"":([0-9]+),"

Used as:

Regex.Match(@"""id"":143331539043251,", @"""id"":([0-9]+),").Groups[1].Value

Which returns 143331539043251.

like image 26
Oded Avatar answered Jun 25 '26 12:06

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!