Search string for percentage

I am using C #. I need a method that will take a string as input, search for a percent character in that string, and then return the number immediately before the percent character. for example "asdf sdfa asf 32% asdf"

will return 32. "asdfl asfi asdf kd 34.5% adsfkjfg"

will return 34.5. I know how to find the index of the percent symbol and then scroll back looking for space and return everything in the middle. I feel like there is probably a more efficient way to do this.

+3


source to share


2 answers


var result = str.Split(' ')
                .Where(s => s.Contains('%'))
                .Select(s => s.Trim('%'));

      

Explanation



Split turns your input string into IEnumerable<string>

, Where selects only those strings that contain the character you are looking for, %

and Select , design each of these elements so that the new elements do not contain the character%

+1


source


You can use Regular Expression to accomplish this using the following pattern:

(^|\s)\d+(.\d+)?(?=%)

      

And in the code:

var match = 
   System.Text.RegularExpressions.Regex.Match(input, @"(^|\s)\d+(.\d+)?(?=%)");

if (match.Success)
{
    string value = match.Value;
}

      

And here's the pattern, broken into pieces:



(^|\s

)
. Indicates that the rest of the template should appear either at the beginning of a line or after a space. As a result, "Hello 3%" will match, but "Hello3%" will not.

\d+

: matches one or more digits.

(.\d+)?

: indicates that , if exists . ", must also be one or more decimal digits.

(?=%)

... The lookgroup is used to match "%" and returns whatever was captured before it (that is, the value).

+1


source







All Articles