Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me build a regex

Tags:

c#

regex

I'm, quite frankly, completely clueless about Regular expression, more so building them. I am reading in a string that could contain any sort of combination of characters and numbers. What I know for certain is, somewhere in the string, there will be a number followed by % (1%, 13% etc.), and I want to extract that number from the string.

Examples are;

[05:37:25] Completed 21% //want to extract 21
[05:32:34] Completed  18000000 out of 50000000 steps (36%). //want to extract 36

I'm guessing I should be using either regex.Replace or regex.Split, but beyond that, I'm not sure. Any help would be appreciated.

like image 591
xbonez Avatar asked Dec 08 '25 06:12

xbonez


2 Answers

You should be able to use something like "(\d+)%". This will match any number of consecutive digit characters, then a percent sign, and will capture the actual number so you can extract and parse it. Use this in Regex.Match(), and browse the Matches array of the result (I think it'll be the second element in the array, index 1).

If you need a decimal point, use "(\d+(\.\d+)?)%", which will match a string of digits, followed by a decimal point, then another set of digits.

like image 157
KeithS Avatar answered Dec 09 '25 20:12

KeithS


The regex you want is:

/(\d+)%/

This will capture any number of digits immediately preceding a percentage sign.

like image 32
CanSpice Avatar answered Dec 09 '25 20:12

CanSpice



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!