How can I matche an string using regex with access and VBA - regex

I have this code, but when I use this, the UrlTest variable return the entire URL and not the capturing groups where I have defined in the regex. ^http:\/\/myanimelist\.net\/animelist\/(.*[^\/])(?:\/|)$
Here is my code:
Private Function UrlTest(strUrl As String) As String
'Do the regEx for get the user in url
Dim regEx As New RegExp
regEx.Pattern = "^http:\/\/myanimelist\.net\/animelist\/(.*[^\/])(?:\/|)$"
regEx.IgnoreCase = True
regEx.Global = False
If regEx.Test(strUrl) Then
Dim matche As Object
Set matche = regEx.Execute(strUrl)
If matche.Count <> 0 Then
UrlTest = matche(0)
End If
Else
UrlTest = "false"
End If
End Function
This function with strUrl with http://myanimelist.net/animelist/example as value return the same value, and not what I want: example.
I can't understand that ! You can see, this Regex test work !

UrlTest = matche(0).submatches(0)
You should try this.

Related

VBA regex - Value used in formula is of the wrong data type

I can't seem to figure out why this function which includes a regex keeps returning an error of wrong data type? I'm trying to return a match to the identified pattern from a file path string in an excel document. An example of the pattern I'm looking for is "02 Package_2018-1011" from a sample string "H:\H1801100 MLK Middle School Hartford\2-Archive! Issued Bid Packages\01 Package_2018-0905 Demolition and Abatement Bid Set_Drawings - PDF\00 HazMat\HM-1.pdf". Copy of the VBA code is listed below.
Function textpart(Myrange As Range) As Variant
Dim strInput As String
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
strInput = Myrange.Value
With regex
.Pattern = "\D{2}\sPackage_\d{4}-\d{4}"
.Global = True
End With
Set textpart = regex.Execute(strInput)
End Function
You need to use \d{2} to match 2-digit chunk, not \D{2}. Besides, you are trying to assign the whole match collection to the function result, while you should extract the first match value and assign that value to the function result:
Function textpart(Myrange As Range) As Variant
Dim strInput As String
Dim regex As Object
Dim matches As Object
Set regex = CreateObject("VBScript.RegExp")
strInput = Myrange.Value
With regex
.Pattern = "\d{2}\sPackage_\d{4}-\d{4}"
End With
Set matches = regex.Execute(strInput)
If matches.Count > 0 Then
textpart = matches(0).Value
End If
End Function
Note that to match it as a whole word you may add word boundaries:
.Pattern = "\b\d{2}\sPackage_\d{4}-\d{4}\b"
^^ ^^
To only match it after \, you may use a capturing group:
.Pattern = "\\(\d{2}\sPackage_\d{4}-\d{4})\b"
' ...
' and then
' ...
textpart = matches(0).Submatches(0)

Why is my regex not working

I tried myself for the first time at an regex expression.
Why doesnt it show the messagebox ("Pls insert a valid mail!") if the text is wrong?
I imported the Regex
Imports System.Text.RegularExpressions
then i wrote my function
Function emailAddressChecker() As Boolean
Dim regex As Regex = Nothing
Dim regExPattern As String = "^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
Dim emailAddress = txtbx_neueEmail.Text
If Regex.IsMatch(emailAddress, regExPattern) Then
Return True
Else
Return False
MessageBox.Show("Pls insert a valid mail!")
txtbx_neueEmail.Text = ""
End If
End Function
then i used my function in an event
Private Sub btn_BestaetigeBearbeitung_Click(sender As Object, e As RoutedEventArgs) Handles btn_BestaetigeBearbeitung.Click
If combx_Auswahl.SelectedIndex = 0 Then
emailAddressChecker()
If emailAddressChecker() = True
MessageBox.Show("Hallo!")
Else
MessageBox.Show("")
End If
Nothing is executed after a Return statement, you should change you code order like this:
Else
MessageBox.Show("Pls insert a valid mail!")
txtbx_neueEmail.Text = ""
Return False
End If

Check input for UCase (RegEx) and convert in UCase if LCase

I'm having the following script:
Function IsValidLetter( Letter )
const IVNAME_TEST = "[A-Z]{1,2}"
Dim regEx, match, myMatches
Set regEx = New RegExp
regEx.Pattern = IVNAME_TEST
regex.IgnoreCase = false
Set myMatches = regEx.Execute( UCase(Letter) )
If myMatches.Count > 0 Then
IsValidLetter = true
End If
End function
It works great, because I want maximum 2 letter from A-Z in an input field. My question; how do I check if the input is lower or uppercase? Best solution would be if it converts it 'on the fly' with this function.
PS: 'Letter' is an input value from a HTML file.
UPDATE:
Sub SetFullName
UppercaseConvert.Value = Letter.Value
CombinedName.Value = Ucase(CombinedName.Value)
End Sub
Works great! :)
Alternatively you could have:
set regex.IgnoreCase = true
or
set IVNAME_TEST = "[A-Za-z]{1,2}"

How to include variable in Regular expression pattern

I am working on a vba macro which uses regular expression to search for a string pattern in another string.
Regex pattern includes a string (APR24 in code below) which varies. I need to know how to include a variable in the pattern.Could any one please help.
My code is as below
Public Function Regexsrch(ByVal str2bsrchd As String, ByVal str2srch As String) As Boolean
Dim Regex As New VBScript_RegExp_55.RegExp
Dim matches, s
Regex.Pattern = "(\.|\s)APR24(,|\s|\()"
Regex.IgnoreCase = True
If Regex.Test(str2bsrchd) Then
Regexsrch = True
Else
Regexsrch = False
End If
End Function
So str2srch is "APR24" or some variation? If that is the case you just use concatenation to build up your pattern string.
Public Function Regexsrch(ByVal str2bsrchd As String, ByVal str2srch As String) As Boolean
Dim Regex As New VBScript_RegExp_55.RegExp
Dim matches, s
Regex.Pattern = "(\.|\s)" + str2srch + "(,|\s|\()"
Regex.IgnoreCase = True
If Regex.Test(str2bsrchd) Then
Regexsrch = True
Else
Regexsrch = False
End If
End Function
You can specify whatever pattern you want in str2srch and then assign that to Regex.Pattern
For example
Sub Sample()
Debug.Print Regexsrch("APR24ddd", "APR24") '<~~ Returns True
Debug.Print Regexsrch("APR277ddd", "APR24") '<~~ Returns False
End Sub
Public Function Regexsrch(ByVal str2bsrchd As String, ByVal str2srch As String) As Boolean
Dim Regex As New VBScript_RegExp_55.RegExp
Dim matches, s
Regex.Pattern = str2srch
Regex.IgnoreCase = True
If Regex.Test(str2bsrchd) Then
Regexsrch = True
Else
Regexsrch = False
End If
End Function
FOLLOWUP
Even if it is dynamic you can always pass the pattern as
Debug.Print Regexsrch("APR24ddd", "(\.|\s)" & VARIABLE & "(,|\s|\()").
This gives you the flexibility of using whatever pattern you want to pass to the function and you are not limited to one pattern...

VB.Net Regular Expressions - Extracting Wildcard Value

I need help extracting the value of a wildcard from a Regular Expressions match. For example:
Regex: "I like *"
Input: "I like chocolate"
I would like to be able to extract the string "chocolate" from the Regex match (or whatever else is there). If possible, I also want to be able to retrieve several wildcard values from a single wildcard match. For example:
Regex: "I play the * and the *"
Input: "I play the guitar and the bass"
I want to be able to extract both "guitar" and "bass". Is there a way to do it?
In general regex utilize the concepts of groups. Groups are indicated by parenthesis.
So I like
Would be I like (.) . = All character * meaning as many or none of the preceding character
Sub Main()
Dim s As String = "I Like hats"
Dim rxstr As String = "I Like(.*)"
Dim m As Match = Regex.Match(s, rxstr)
Console.WriteLine(m.Groups(1))
End Sub
The above code will work for and string that has I Like and will print out all characters after including the ' ' as . matches even white space.
Your second case is more interesting because the first rx will match the entire end of the string you need something more restrictive.
I Like (\w+) and (\w+) : this will match I Like then a space and one or more word characters and then an and a space and one or more word characters
Sub Main()
Dim s2 As String = "I Like hats and dogs"
Dim rxstr2 As String = "I Like (\w+) and (\w+)"
Dim m As Match = Regex.Match(s2, rxstr2)
Console.WriteLine("{0} : {1}", m.Groups(1), m.Groups(2))
End Sub
For a more complete treatment of regex take a look at this site which has a great tutorial.
Here is my RegexExtract Function in VBA. It will return just the sub match you specify (only the stuff in parenthesis). So in your case, you'd write:
=RegexExtract(A1, "I like (.*)")
Here is the code.
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String) As String
Application.ScreenUpdating = False
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
RegexExtract = allMatches.Item(0).submatches.Item(0)
Application.ScreenUpdating = True
End Function
Here is a version that will allow you to use multiple groups to extract multiple parts at once:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String) As String
Application.ScreenUpdating = False
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
Dim i As Long
Dim result As String
RE.Pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.Item(0).submatches.count - 1
result = result & allMatches.Item(0).submatches.Item(i)
Next
RegexExtract = result
Application.ScreenUpdating = True
End Function