I have many string format as : RGB:ABC.XX,DEF.XX,GHI.XX where ABCDEFGHI are numbers.
I need to extract the R (ABC), G (DEF), B (GHI) from that String The problem is that the string can take many form like
RGB:AB.XX,DE.XX,GHI.XX
RGB:ABC.XX,DE.XX,GH.XX
RGB:ABC.XXX,DE.XX,GH.XX
RGB:ABC.XXX,DE.XX,GH.XX
...
...
...
So as you can see, there's many thing to consider to extract this rbg from that string.
I tried to use LINQ but that will be a mess I think (That is only for the first 'R' (red)):
rgb[0] = new String(rgbName.SkipWhile(x => char.IsLetter(x) || x == ':').TakeWhile(x => char.IsNumber(x)).ToArray());
Is there a more efficient way to do that? Maybe regex can do that thing but i'm not an expert. Any help will be appreciate.
Thanks.
You can try this regex
.*?(?<R>\d+).*?(?<G>\d+).*?(?<B>\d+)
You can access the group like this
Regex.Match(input,regex).Groups["R"].Value;//Red value
Luckily, only a limited degree of regex expertship is required for this, so give it a try:
What you need to know:
()
encloses a capturing group - from the complete match, you will be able to extract those as single strings []
encloses a set of allowed characters \\.
is a fullstop (escaped, because it otherwise has a special meaning outside of []
in C#'s regex implementation) \\
in general is used for escaping special characters +
means one or more times of the preceding sub-expression ^
and $
denote the beginning and the end of the string, respectively With that in mind, you can try the following regular expression:
^RGB\:([0-9]+)\.[0-9]+\,([0-9]+)\.[0-9]+\,([0-9]+)\.[0-9]+$
Use this to invoke the Match
method of the Regex
class .
The resulting Match
instance has a Groups
property which should contain four elements:
Every such item is an instance of the Group
class . Use its Value
property to retrieve the matched string.
Yep, regex will be ideal but until you learn that, work with what you (and an average developer) know.
Break the problem into smaller ones
- Remove the "RGB:" part
- Split the string into an array of strings with delimiter the comma (,)
- Get the values from each string in the array
The best solution is not the one with the fewer lines of code. It's the one that can be understood by any developer who will later has to read your code.
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.