PDA

View Full Version : Match a pattern



Jfp87
09-02-2016, 05:52 AM
Guys,

I have a list of node names in a table column. I am trying to parse the list to show that each node name matches a particular format. The format is as follows:

Format 1) n[1-100]-[1-20]-[1-10] OR
Format 2) n[1-100]-[1-20]

I.e., the node name can have three parts (format 1) or two parts (format 2), but not one part. The first part is always prefixed by "n".

Some examples:

n1-1
n1-1-1
n100-20-10
n87-14-2
n50-4

It's the pattern matching which is bogging me down. I think I can get it to match the pattern using simple string functions like Len, Right, Mid, InStr etc., but is this the best way - what about RegEx?

Joe

gmaxey
09-02-2016, 10:49 AM
Joe,

Not saying this is best but is seems t work:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oPar As Paragraph
Dim oRng As Range
Dim strText As String
Dim arrParts() As String
For Each oPar In ActiveDocument.Paragraphs
If oPar.Range.Characters(1) = "n" Then
Set oRng = oPar.Range
oRng.Start = oRng.Start + 1
oRng.End = oRng.End - 1
strText = oRng.Text
arrParts = Split(strText, "-")
If UBound(arrParts) > 0 And UBound(arrParts) < 3 Then
If IsNumeric(arrParts(0)) And arrParts(0) < 101 Then
Beep
If IsNumeric(arrParts(1)) And arrParts(1) < 21 Then
Beep
If UBound(arrParts) = 2 Then
If IsNumeric(arrParts(2)) And arrParts(2) < 11 Then
Beep
Else
'Invalid
End If
End If
Else
'Invalid
End If
Else
'Invalid
End If
Else
'Invalid
End If
Else
'Invalid
End If
Next
lbl_Exit:
Exit Sub
End Sub

Jfp87
09-03-2016, 05:08 AM
That helped me out Greg, thanks. There is always so many ways to do one task.

Joe