Visual Basic 正则表达式问题 [英] Visual Basic Regular Expression Question
问题描述
我有一个字符串列表.当用户输入字符时,程序会在文本框中显示列表中所有可能的字符串.
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)
例如如果用户输入 a,p,l,e,r ,那么程序将显示苹果和梨.它应该匹配输入了所有字母的任何条目,无论顺序如何,也无论其他字母如何.我应该向 rx 添加什么?如果使用正则表达式无法实现,请指定任何其他方法来执行此操作.
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.
推荐答案
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())
正则表达式方法:
匹配结果的正则表达式模式类似于:
A regex pattern to match the results would resemble something like:
"^[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))
这篇关于Visual Basic 正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!