5

I have a list of string. When user inputs chars in, the program would display all possible strings from the list in a textbox.

Dim fruit as new List(Of String) 'contains apple,orange,pear,banana
Dim rx as New Regex(fruit)

For example If user enters a,p,l,e,r , then the program would display apple and pear. It should match any entry for which all letters have been entered, regardless of order and regardless of additional letters. What should I add to rx? If it's not possible with Regular Expressions, then please specify any other ways to do this.

10
  • 2
    Why do apple and pear appear and not the others? Commented Jun 7, 2011 at 12:42
  • Is the order of the input characters relevant? E.g. a,p,l matches apple but p,l,a does not? And: should pear really match in your example? Because there is a l in your character list. Commented Jun 7, 2011 at 12:45
  • Because user didn't entered o,n,g for orange and b,n for banana. The idea is to display all words, which chars have been entered. Commented Jun 7, 2011 at 12:45
  • But a is in orange, and l is not in pear. So why does pear match and orange not? Commented Jun 7, 2011 at 12:46
  • 2
    @Andrew: Sounds like it should match any entry for which all distinct letters have been entered, regardless of order and regardless of additional letters. Commented Jun 7, 2011 at 12:48

1 Answer 1

7

LINQ Approach:

Dim fruits As New List(Of String) From { "apple", "orange", "pear", "banana" }
Dim input As String = "a,p,l,e,r"
Dim letters As String = input.Replace(",", "")
Dim result = fruits.Where(Function(fruit) Not fruit.Except(letters).Any())

Regex Approach:

A regex pattern to match the results would resemble something like:

"^[apler]+$"

This can be built up as:

Dim fruits As New List(Of String) From { "apple", "orange", "pear", "banana" }
Dim input As String = "n,a,b,r,o,n,g,e"
Dim letters As String = input.Replace(",", "")
Dim pattern As String = "^[" + letters + "]+$"
Dim query = fruits.Where(Function(fruit) Regex.IsMatch(fruit, pattern))
Sign up to request clarification or add additional context in comments.

8 Comments

Wouldn't this fail for pear? Also, it seems to me that it would return any word that contained a,p,l,e but also contained other letters - like maple.
@Joel your comment is correct. I missed the clarification in the OP's comments.
@Joel check out the update approach. It should now take those issues into account.
How can I display the results in a textbox?
@Cobold you need to loop over the results and append them to the textbox... or if you want to display them as a comma separated list of items you could use Dim text As String = String.Join(", ", result)
|

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.