0

I have a list of material numbers like:

JU9900
I78
JU9
JU990
TX90

and a string like ...bla_bla, JU9900 / TX / TX90, JU990 bla_bla...

The goal is to find all material numbers that are in the string. So for the example above this whould be JU9900, JU990, and TX90. At the moment I also get the JU9 as a hit which is wrong.

1
  • 3
    Welcome to SO, please provide source code to help us understand how you are trying to achieve this. also, what have you tried so far to fix this issue? Commented Mar 12, 2020 at 8:04

1 Answer 1

1

You want to search whole 'words' only, so you have to take the word boundaries (\b) into account. See for the example: https://regex101.com/r/1H20Mx/1

As a console application:

Sub Main()
    Dim Materials As List(Of String) = New List(Of String)
    Materials.Add("JU9900")
    Materials.Add("I78")
    Materials.Add("JU9")
    Materials.Add("JU990")
    Materials.Add("TX90")

    Dim FoundMaterials As List(Of String) = GetMaterials(Materials, "...bla_bla, JU9900 / TX / TX90, JU990 bla_bla...")

    For Each Material In FoundMaterials
        Console.WriteLine(Material)
    Next
    Console.Read() ' keep console open and wait for user to exit
End Sub

Private Function GetMaterials(Materials As List(Of String), Input As String) As List(Of String)
    Dim FoundMaterials As List(Of String) = New List(Of String)

    Dim TestPattern As String = ""
    For Each Material As String In Materials
        ' escape any RegEx-characters in the Material's name
        TestPattern &= System.Text.RegularExpressions.Regex.Escape(Material) & "|"
    Next
    TestPattern = TestPattern.Trim("|"c) ' remove the | at the end

    For Each TestMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(Input, "\b(" & TestPattern & ")\b")
        FoundMaterials.Add(TestMatch.Value)
    Next

    Return FoundMaterials
End Function
Sign up to request clarification or add additional context in comments.

1 Comment

That's VB.NET, the OP asks about VBA.

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.