Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Basic Regular Expression Question

Tags:

regex

vb.net

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.

like image 252
Cobold Avatar asked Jun 07 '11 12:06

Cobold


1 Answers

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))
like image 178
Ahmad Mageed Avatar answered Oct 06 '22 08:10

Ahmad Mageed