I have a string of the format
[00:26:19] Completed 80000 out of 500000 steps 开发者_StackOverflow中文版(16%)
from which I want to get the 16
part.
Should I search for ( and then get the % and get the portion in between, or would it be wiser to set up a regex query?
RegEx is probably going to be the trend, but I don't see a good reason for it, personally.
That being said, this should work:
String s = "[00:26:19] Completed 80000 out of 500000 steps (16%)";
Int32 start = s.LastIndexOf('(') + 1;
Console.WriteLine(s.Substring(start,s.LastIndexOf('%')-start));
And you can Convert.ToInt32()
if you feel it necessary.
I would use a regular expression like this:
([^%]+)%\)$
This expression would allow non-numeric data to be captured - if you are certain that the text within the parenthesis and just to the left of the percentage will always be a number you can simplify the expression to this:
(\d+)%\)$
Another Fast way is...
string s = "[00:26:19] Completed 80000 out of 500000 steps (16%)";
string res = s.Split("(%".ToCharArray())[1];
this assumes we will only see '(' and '%' once in the string
It depends on how variable you expect the input string (the "haystack") to be, and how variable you expect your target pattern (the "needle") to be. Regexes are extremely useful for describing a whole class of needles in a largely unknown haystack, but they're not the right tool for input that's in a very static format.
If you know your string will always be something like:
"[A:B:C] Completed D out of E steps (F%)"
where 1) A-F are the only variable portions, and 2) A-F are always numeric, then all you need is a little string manipulation:
int GetPercentage(string str)
{
return int.Parse(
str.Substring(
str.IndexOf('(') + 1,
str.IndexOf('%') - str.IndexOf('(')
)
);
}
The key question here is: "Are the presence of (
and %
sufficient to indicate the substring I'm trying to capture?" That is, will they only occur in that one position? If the rest of the haystack might contain (
or %
somewhere, I'd use regex:
@"(?<=\()\d+(?=%\)))$"
精彩评论