2

I am working on a vb.net utility and have run into a need to find all the distinct strings inside a string.

So basically I will have a string that will look like this. 1.875{0};10;0.25|1.875;9;0.25|{2}1.875;1.875;0.25|14.125;{1}1.875;0.25|{0}14.125;16.125{1};0.25|1.875;{0}16.125;0.25|1.875;9;0.25{2}|1.875;8;0.25

So you can see I have these chars inside the string {0}, {1}, {2}

There are however multiples of each "placeholder" so to speak.

So i need help writing a function that will take string string above and return a count of 3 in this example, because there are 3 distinct placeholders in the source string. It would kind of mimick the distinct command in sql.

I'm sure this uses some kind of regex but I can't wrap my head around it to retrieve only the distinct ones. Not all the multiples.

Any help is appreciated. Thanks in Advance.

2 Answers 2

2

Using regular expressions and a little bit of LINQ you can achieve the desired effect

Imports System.Text.RegularExpressions
Imports System.Linq

Private Function CountPlaceholders(source As String) As Integer
    Dim matches As MatchCollection = Regex.Matches(source, "{[0-9]+}")
    Return matches.Cast(Of Match)().Select(Function(m) m.Value).Distinct().Count()
End Function

First, find all the placeholders using a fairly straightforward regular expression. The + after the [0-9] numeric search will find one or more occurrences of a number so will find placeholders 0 through n.

The next line is what counts the distinct occurrences. Each item in the matches MatchCollection has to be cast to Match in order for the LINQ-to-Objects extensions to operate. After that, you select the Value property of the Match object, filter the distinct values, and count them.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you very much. Taught me something new.
0

Yes you can use the regex {\d+} to do the match, but you are correct that will not give you a distinct list. But you can loop over the Match collection returned by Regex.Matches, extract the Value and use the Distinct Linq method to get a list of the distinct entries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.