Trying to match this data, that is contained in one string:
vsan 1 interfaces:
fc2/1
vsan 10 interfaces:
fc1/1 fc1/2 fc1/3 fc1/4
fc1/5 fc1/6 fc1/7 fc1/8
fc1/9 fc1/10 fc1/11 fc1/12
fc1/13 fc1/14 fc1/15 fc1/16
The output I am getting is correctly grouped by each vsan, but I am only getting the first interface (fcnn/nn) in each. For instance, in vsan 10 I want all the interfaces but I am only getting fc1/1.
Here is the Regex I am using:
string MemberMatchString =
@"vsan\s(?<number>\d+)[\s]interfaces:\n\s+(?<interfaces>\sfc\d+/\d+)\s+\n?";
MatchCollection MemberList = Regex.Matches(block, MemberMatchString);
it tink the best solution would be a Tokenizer/Parser to get the Information you want.
I don’t think you can handle it (efficient and transparent for others) with a single Regex. In my opinion a Regex is not always the Solution for complex string problems.
I also think, that a large Regex is not maintainable at any time and should therefore be avoided. (Try it by yourself, get any complex Regex from any Page from the Internet. Don’t read, what the expression should do, and try describing the functionality of the expression. You would be supprised what the writer expected, and what you expect the expression to do.
Simple Regex to bold my point:
What does this Regex do?
This Regex is the implementation of the
RFC 2822from this page.And this one is a reduced one from the same page.
Both can be used to check a e-mail address! Did you expect this?
Solution:
Create a Tokenzier/Parser: So to show you how i would solve this problem I prepared a working sample for you.
Just Copy paste it to a Console Application, should work fine 🙂
Please give me feedback about my code and if my helps was usefull for you.
Sample explanation:
Create a Tokenizer, which splits the expressions into matching tokens. In this case the Tokens derive from Interface
IToken.The Tokens are created by Line and than by a regex Match with groups. See method
TokenizeandTokenizeLine. They do the hard work.After Splitting it up it gets real simple. Just move forward through the Tokens and create the
VSanandInterfaceObjects.The Tokens are order after the order of the String Groups (defined by Regex in Tokenize) so moving through the list is always:
So you can easy create a VSan Object and adding all Interfaces afterwards. If the next VSan Token is in line just create a new VsanObject an continue with adding Interfaces to the new Instance.
Now you have a list of Vsans which contains a List of Interfaces which you can use .
I overwrote the
ToStringMethod to make the result visible.Sample Code:
Result and Conclusion:
As a result you get a IVsan which contains the IInterfaces. You can use this Model in your code to get Information you looking for.
without changing anything in your business logic.
Please ask me if you have furhter questions, i would be glad helping you! Please also give me feedback, I’m open for new impressions!