Visual Basic正则表达式问题

时间:2011-06-07 12:36:34

标签: regex vb.net

我有一个字符串列表。当用户输入字符时,程序将在文本框中显示列表中的所有可能字符串。

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

例如,如果用户输入 a,p,l,e,r ,则程序将显示apple和pear。 它应匹配所有输入所有字母的条目,无论顺序如何,无论其他字母如何。 我应该添加什么到rx?如果使用正则表达式无法实现,请指定其他任何方法。

1 个答案:

答案 0 :(得分:7)

LINQ方法:

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())

正则表达式方法:

匹配结果的正则表达式模式类似于:

"^[apler]+$"

这可以建立为:

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))