我有2个字符串数组,如下所示(B是A的子集),并尝试从A提取B上的匹配元素
A = ["1.1","1.1.1","1.1.2","1.1.3","1.2","1.3","1.4",....]
B = ["1.1.*","1.2"]
This should return ["1.1.1","1.1.2","1.1.3","1.2"]
我的示例尝试解决此问题:
Dim regEx As New Regex("1.1.*")
Console.WriteLine(regEx.IsMatch("1.1.1")) 'TRUE which is Expected
Console.WriteLine(regEx.IsMatch("1.1")) 'TRUE - Expected is FALSE
答案 0 :(得分:0)
Dim A() As String = {"1.1.1","1.1.2","1.1.3","1.2","1.3","1.4"}
Dim B() As String = {"1.1.*","1.2"}
Dim isMatch = Function(str As String, patterns() As String)
For Each pattern As String In patterns
If pattern.Contains("*") Then
Dim regexPattern As String = "^" & pattern.Replace(".","\.").Replace("*", "\d+") & "$"
If Regex.IsMatch(str, regexpattern) Then Return True
Else
If str.Equals(pattern) Then Return True
End If
Next
Return False
End Function
Dim result = A.Where(Function(s) isMatch(s, B))
这里的技巧是使用正则表达式而不是Like运算符。为了使用正则表达式,需要通过将每个点替换为\.
和*替换为\d+
来将模式(B个数组项)重构为正则表达式模式。 \d+
将匹配任何长度的任何数字。