regex issue in extract M followed by 8 digits [closed] - excel

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
excel value=M#9094562;M 0567468;M25969028;M25969029;Mployee e
Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "m[0-9]{8}"
If strPattern <> "" Then
strInput = Myrange.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function

Use a regex tester to check what you are getting. https://regexr.com/
Your current Regex only matches 2 occurrences in your pattern.
The others contain a space and a hash, and one only has 7 digits. If you want to find these as well you can expand your pattern.
m.?[0-9]{7,8}
But, if you truly want M followed by 8 digits (M12345678) then your pattern works.
Your Excel code is wrong... you are not looping through the matches (see below):
If regEx.Test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
You need to loop through the matches in the string (see below):
Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
'Added to store matches
Dim objRegMC As Object
Dim objRegM As Object
Dim intCounter As Integer
Dim strDelimiter As String
intCounter = 1
strDelimiter = "|"
strPattern = "m[0-9]{8}"
If strPattern <> "" Then
strInput = Myrange.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
'Store matched string and loop through matches
Set objRegMC = regEx.Execute(strInput)
For Each objRegM In objRegMC
'Do what you want here to split values etc.
'I have added a delimiter, you can do whatever you want
If objRegMC.Count > 1 Then
If intCounter = objRegMC.Count Then
simpleCellRegex = simpleCellRegex & objRegM
Else
simpleCellRegex = simpleCellRegex & objRegM & strDelimiter
End If
intCounter = intCounter + 1
Else
simpleCellRegex = objRegM
End If
Next
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
Results below:

Related

VBA match on IP and write to cell not working

writing macro to extract IP out of many cells and buried in text. I need to find the IP and then copy each to a new blank cell.
I get the results "not matched". Please advise as I'm over thinking this.
To test I filled 40 cells with "this is a ip test 8.8.8.8 oh no"
Private Sub simpleRegex()
Dim strPattern As String: strPattern = "\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b" 'find IP
Dim Match As Object
Dim matches As Object
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("A1:A39") 'within this range
Dim i As Long, strMatches As String
i = 1 'row number where we start to write
For Each cell In Myrange
If strPattern <> "" Then
strInput = cell.Value
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regex.Test(strInput) Then 'if ip found do this
Set matches = regex.Execute(strInput)
strMatches = vbNullString
For Each Match In matches
'strMatches = strMatches 'collect all matches ip?
Worksheets("Sheet1").Range("U" & i).Value = strMatches 'write the matches into cell
i = i + 1
Next
Else
MsgBox ("Not matched")
End If
End If
Next
End Sub
This works for me (re-arranged the output a bit)
Private Sub simpleRegex()
Dim strPattern As String:
Dim Match As Object
Dim matches As Object
Dim strMatches As String
Dim regex As Object
Dim strInput As String
Dim Myrange As Range, cell As Range, cOut as Range
Set regex = CreateObject("VBScript.RegExp")
strPattern = "\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b" 'find IP
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
Set cOut = ActiveWorkbook.Worksheets("Sheet2").Range("A1") 'start output here
Set Myrange = ActiveSheet.Range("A1:A39") 'within this range
For Each cell In Myrange
strInput = cell.Value
If Len(strInput) > 0 Then
If regex.Test(strInput) Then 'if ip found do this
Set matches = regex.Execute(strInput)
strMatches = vbNullString
For Each Match In matches
cOut.Value = Match.Value 'write the match into cell
Set cOut = cOut.Offset(1, 0)'next cell down
Next
Else
'cell.Offset(0, 1).Value = "No matches"
End If
End If
Next
End Sub

Removing first set of numbers in string

I have a list of items:
B100Q91, B75NX2, BR100, XN20ZN..
I want to remove the first set of numbers in every item, so that it looks like this:
BQ91, BNX2, BR, XNZN..
My approach looks like this:
Function RemoveFirstNumbers(Txt As String) As String
With CreateObject("VBScript.RegExp")
Dim posn As Integer
posn = GetPositionOfFirstNumericCharacter(Txt)
1
If (IsError(posn)) = True Then Replace(Txt, 1, 1) As String
Dim posn As Integer
Else
End With
End Function
End If
GoTo 1
with
Public Function GetPositionOfFirstNumericCharacter(ByVal s As String) As Integer
Dim i As Integer
For i = 1 To Len(s)
Dim currentCharacter As String
currentCharacter = Mid(s, i, 1)
If IsNumeric(currentCharacter) = True Then
GetPositionOfFirstNumericCharacter = i
Exit Function
End If
Next i
End Function
EDIT to package the below as a function
Function ReplaceFirstDigits(sLookupExpression) as String
Dim oReg As Object
Set oReg = CreateObject("VBScript.Regexp")
With oReg
.Global = True
.ignorecase = True
.MultiLine = False
.Pattern = "([A-Za-z]+)(\d+)(\w*)"
End With
ReplaceFirstDigits = oReg.Replace(sLookupExpression, "$1$3")
End Function
Then you can call the function directly from the spreadsheet with a standard syntax, such as =ReplaceFirstDigits(A1)
If you wanted to use a regular expression, code such as the following might do the trick for you.
Sub Test()
Dim oReg As Object
Set oReg = CreateObject("VBScript.Regexp")
With oReg
.Global = True
.ignorecase = True
.MultiLine = False
.Pattern = "([A-Za-z]+)(\d+)(\w*)"
End With
Debug.Print oReg.Replace(Selection, "$1$3")
End Sub
EDITED:
If you don't want to use RegExp, just straight VBA:
Option Explicit
Function RemoveFirstNumber(strInput As String) As String
Dim strRet As String
Dim bFirstNumber As Boolean
bFirstNumber = False
Dim strChar As String
Dim nChar As Integer
For nChar = 1 To Len(strInput)
strChar = Mid(strInput, nChar, 1)
If IsNumeric(strChar) Then
bFirstNumber = True
Else
If bFirstNumber Then
strRet = strRet & Mid(strInput, nChar)
Exit For
End If
strRet = strRet & strChar
End If
Next nChar
RemoveFirstNumber = strRet
End Function

How to return regular expression match without letters

I have the below code
Function simpleCellRegex(Myrange As Range) As String
Set regEx = CreateObject("VBScript.RegExp")
'Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "_[a-zA-Z][0-9]"
If strPattern <> "" Then
strInput = Myrange.Value
strReplace = "_"
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
Right now, the strReplace variable is hard-coded. Is there a way to replace the matched substring with the same substring without letters?
Ie.,
If the Input is
"bs_oper36_a01"
I would like to output
"bs_oper36_01". However the last several characters could change, so would it be possible to make the output dynamic, ie., if the input changes?

Use Regex to find and delete a string - but leave the last character

I would like to find the "strPattern" string below, but use REPLACE to replace only "strPattern1" - which is effectively "strPattern" excluding the last character.
Dim strPattern As String: strPattern = "^\d{1,2}.\d{1,2}\s\OS\s[MCVH]"
Dim strPattern1 As String: strPattern1 = "^\d{1,2}.\d{1,2}\s\OS"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("B1", Range("b1").End(xlDown))
For Each cell In Myrange
If strPattern <> "" Then
strInput = cell.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
cell.Offset(0, 0) = regEx.Replace(strInput, strReplace)
End If
End If
Next
Thank you in advance for your help
You need to use fields in your search string '()'. e.g. "(^\d{1,2}.\d{1,2}\s\OS\s)([MCVH])". Your replace string would be "$2".

Nested for...each loops with If statements

I am new to vb.script so this may just be a formatting question that I cannot find the answer.
The problem is validating data in cells that are on different sheets in the same workbook.
Looping through worksheets and then looping through the cell range:
Private Sub Validate(ByRef objWorkbook As Workbook)
Dim strPattern As String: strPattern = "^\-{0,1}\d+(.\d+){0,1}$"
Dim regEx As New VBScript_RegExp_55.RegExp
Dim strInput As String
Dim strOutput As String
Dim Myrange As Range
Dim regExCount As Object
Set regExCount = CreateObject("vbscript.regexp")
On Error Resume Next
For Each objWorksheet In objWorkbook.Worksheets
If (UCase(objWorksheet.Name) = "Foo") Then
objWorksheet.Select
Range("Q2").Select
ElseIf (UCase(objWorksheet.Name) = "Bar") Or (UCase(objWorksheet.Name) = "Poo") Then
objWorksheet.Select
Set Myrange = ActiveSheet.Range("D51:AA76")
For Each cell In Myrange.Cells
If strPattern <> "" Then
strInput = cell.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
Set regExCount = regEx.Execute(strInput)
If regExCount.Count = 0 Then
strOutput = strOutput + "Illegal character at " + cell.AddressLocal + "\r\n"
End If
Next cell
End If
Next
MsgBox (strOutput)
End Sub
When I compile I get an error of a Next without a For loop at the Next Cell. Removing that line and I get an error for Block If without an End Ff highlighting the End Sub. Adding an End If before the End sub and I get a Next without a For error.
Isn't it this block missing and end if?
If strPattern <> "" Then
strInput = cell.Value
strReplace = ""
Your
If strPattern <> "" Then
is not closed between
End If ' regExCount.Count
Next cell ' In Myrange.Cells

Resources