VB.NET string.contains using wildcards - string

I Noticed that in a loop inside treeview items , when i am using string.contains method parallel with a textbox that i enter the search string in order to highlight finded nondes , i cant use any wildcard like * or % ... is there any other way to use wildcards ?
What i have tried is having multiple textboxes ex. textbox_x, textbox_y and multiple string.contains in the code string.contains(x) or string.contains(y) but that obviusly doesnt meet my needs because the user may want to use numerous wildcard combinations..

This is a simple function that allows the use of * as jokers at any position
(using regex, here also set to case-insensitive).
Public Shared Function TestSimplePattern(value As String, pattern As String) As Boolean
If String.IsNullOrEmpty(value) Or String.IsNullOrEmpty(pattern) Then Return False
Dim parts = pattern.Split("*")
Dim rxPattern = String.Join(".*?", parts.Select(Function(item) Regex.Escape(item)).ToArray)
rxPattern = "^" & rxPattern & "$"
Return Regex.IsMatch(value, rxPattern, RegexOptions.IgnoreCase)
End Function
Can be used like this:
TestSimplePattern("VB.NET string.contains using wildcards", "*wildcards") ' true
TestSimplePattern("VB.NET string.contains using wildcards", "*string*using*") ' true
TestSimplePattern("VB.NET string.contains using wildcards", "*string*using") ' false

Related

Excel find and replace function correct formula

I wish to use the find and replace function in excel to remove example sentences from cells similar to this:
text <br>〔「text」text,「text」text〕<br>(1)text「sentence―sentence/sentence」<br>(2)text「sentence―sentence」
Sentences are in between 「」brackets and will include a ― and / character somewhere inside the brackets.
I have tried 「*―*/*」 however this will delete everything from the right of the〔
Is there any way to target and delete these specific sentence brackets, with the find and replace tool?
Desired outcome:
text <br>〔「text」text,「text」text〕<br>(1)text<br>(2)text「sentence―sentence」
Quite a long formula but in Excel O365 you could use:
=SUBSTITUTE(CONCAT(FILTERXML("<t><s>"&SUBSTITUTE(CONCAT(IF(MID(A1,SEQUENCE(LEN(A1)),1)="「","</s><s>「",IF(MID(A1,SEQUENCE(LEN(A1)),1)="」","」</s><s>",MID(A1,SEQUENCE(LEN(A1)),1)))),"<br>","|$|")&"</s></t>","//s[not(contains(., '「') and contains(., '―') and contains(., '/') and contains(., '」'))][node()]")),"|$|","<br>")
As long as you have access to CONCAT you could also do this in Excel 2019 but you'll have to swap SEQUENCE(LEN(A1)) for ROW(A$1:INDEX(A:A,LEN(A1)))
This formula won't work in many cases, but if the string has matching rules as in your example, then try this:
=SUBSTITUTE(C5,"「" & INDEX(TRIM(MID(SUBSTITUTE(","&SUBSTITUTE(C5,"」","「"),"「",REPT(" ",99)),(ROW(A1:INDEX(A1:A100,LEN(C5)-LEN(SUBSTITUTE(C5,"」",""))))*2-1)*99,99)),MATCH("*―*/*",TRIM(MID(SUBSTITUTE(","&SUBSTITUTE(C5,"」","「"),"「",REPT(" ",99)),(ROW(A1:INDEX(A1:A100,LEN(C5)-LEN(SUBSTITUTE(C5,"」",""))))*2-1)*99,99)),0)) & "」","")
explain how it works:
split the string between the characters "「 "and "」" into an array
use match("*―*/*",,0) to find the string position (note that it will only return one value if it exists, if you have multiple strings, you can replace match("*―*/*",) with search ("*―*/*",..) and use it as an extra column to get matches string)
Use the index(array,match("*―*/*",..)) to get the string needs replacing (result)
Replace the original string with the results found =substitute(txt,result,"")
Or,
In B1 enter formula :
=SUBSTITUTE(A1,"「"&TRIM(RIGHT(SUBSTITUTE(LEFT(A1,FIND("」",A1,FIND("/",A1))),"「",REPT(" ",99)),99)),"")
You did not tag [VBA], but if you are not averse, you could write a User Defined Function that would do what you want using Regular Expressions.
To enter this User Defined Function (UDF), alt-F11 opens the Visual Basic Editor.
Ensure your project is highlighted in the Project Explorer window.
Then, from the top menu, select Insert/Module and
paste the code below into the window that opens.
To use this User Defined Function (UDF), enter a formula like =replStr(A1) in some cell.
Option Explicit
Function replStr(str As String) As String
Dim RE As Object
Const sPat As String = "\u300C(?:(?=[^\u300D]*\u002F)(?=[^\u300D]*\u2015)[^\u300D]*)\u300D"
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.Pattern = sPat
replStr = .Replace(str, "")
End With
End Function

how to format many emails with regex using vba

With vba, i want to validate many emails between then with semicolon,every mail must end with #customercurrency.com and user can put 2 or 3 or 4 or many emails as he want.
Example : aung#customercurrency.com;thet#customercurrency.com;htoo#customercurrency.com
My code is here.But it might be something wrong.
Public Function ValidateEmailAddressWithSemi(ByRef strEmailAddress As String) As Boolean
'Create Regular expression object
Dim objRegExp As New RegExp
'Set Case insensitive
objRegExp.IgnoreCase = True
objRegExp.pattern = "^\s?([_a-z0-9-]+(.[a-z0-9-]+)#customconcurrency.com)+([;.]([_a-z0-9-]+(.[a-z0-9-]+)#customconcurrency.com)*$"
ValidateEmailAddress = objRegExp.Test(strEmailAddress)
End Function
try this pattern :
"^\s?([_a-z0-9-]+(.[a-z0-9-]+)#customercurrency.com)+([;.]([_a-z0-9-]+(.[a-z0-9-]+)#customercurrency.com))*$"
(mistake in the domain name and a paranthesis is missing)

Excel formula function to remove spaces between characters

In Excel sheet i did a form that customer need to fill out, i have a cell that the customer need to enter his Email Address, I need to data validate the cell as much i can and am nearly success this is what i did:
' this formula is for email structuring
=ISNUMBER(MATCH("*#*.???",A5,0))
' this formula to check if there is spaces at start and the end
=IF(LEN(A5)>LEN(TRIM(A5)),FALSE,TRUE)
But if i right for example (admin#ad min.com) the second formula will not detect the space between the email address, any clue?
Use SUBSTITUTE()
=IF(LEN(A5)>LEN(SUBSTITUTE(A5," ","")),FALSE,TRUE)
How about:
=IF(LEN(A5)>LEN(SUBSTITUTE(A5," ","")),FALSE,TRUE)
based on Jeeped's comment:
=A5=SUBSTITUTE(A5," ","")
You can use VBA to perform validation using regular expressions - after removing any spaces.
Option 1
Returning a Boolean True/False
Public Function validateEmail(strEmail As String) As Boolean
' Remove spaces
strEmail = Replace(strEmail, " ", "")
' Validate email using regular expressions
With CreateObject("VBScript.RegExp")
.ignorecase = True
.Pattern = "^[-.\w]+#[-.\w]+\.\w{2,5}$"
If .test(strEmail) Then validateEmail = True
End With
End Function
This can be used as a normal worksheet function such as:
=validateEmail("yourEmail#test.com")
=validateEmail($A1)
Can also be used in VBA as well
debug.print validateEmail("yourEmail#test.com")
Option 2
Returning the email itself, or return False
If you would prefer that it returns the validated email instead of a Boolean (true/False), then you can do something like:
Public Function validateEmail(strEmail As String) As Variant
' Remove spaces
strEmail = Replace(strEmail, " ", "")
' Validate email using regular expressions
With CreateObject("VBScript.RegExp")
.ignorecase = True
.Pattern = "^[-.\w]+#[-.\w]+\.\w{2,5}$"
If .test(strEmail) Then
validateEmail = strEmail
Else
validateEmail = False
End If
End With
End Function
So, using in a worksheet function for example, using =validateEmail("yourEmail # test.com") will return the string: yourEmail#test.com. However, if the email is invalid such as validateEmail("yourEmailtest.com") then it will return False.
Why use Regular Expressions? Checking for a simple # in the string to validate an email is only a minimal workaround. A string input such as ()#&&*^$#893---------6584.ido would match your =ISNUMBER(MATCH("*#*.???",A5,0)) formula, yet that is obviously not a valid email. Obviously there is no way to 100% validate an email - however, this does a decent job at at the very least ensuring the email could be valid.

Check if cell is only a-z excel

I would like to be sure that all my cell contain only characters (A-Z/a-z). I want to be sure there isn't any symbol, number or anything else. Any tips?
For example I have this "Š".
As a VBA function, the following should work:
Option Compare Binary
Function LettersOnly(S As String) As Boolean
LettersOnly = Not S Like "*[!A-Za-z]*" And S <> ""
End Function
In using the function, S can be either an actual string, or a reference to the cell of concern.
EDIT: Also, you want to be certain you have not set Option Compare Text in your code. The default is Option Compare Binary which is what you want for this type of comparison. I have added that to the code for completeness.
Open the VBA editor (Alt+F11) and create a new module.
Add a reference to "Microsoft VBScript Regular Expressions 5.5" (Tools -> References).
In your new module, create a new function like this:
Function IsAToZOnly(inputStr As String) As Boolean
Dim pattern As String: pattern = "^[A-Za-z]*$"
Dim regEx As New RegExp
regEx.pattern = pattern
IsAToZOnly = regEx.Test(inputStr)
End Function
Use the new function in your worksheet:
=IsAToZOnly(A1)

Stack overflow when replacing ' with '' in VB 6.0

I'm looking into some legacy VB 6.0 code (an Access XP application) to solve a problem with a SQL statement by the Access app. I need to use replace single quotes with 2 single quotes for cases where a customer name has an apostrophe in the name (e.g. "Doctor's Surgery":
Replace(customerName, "'", "''")
Which will escape the single quote, so I get the valid SQL:
SELECT blah FROM blah WHERE customer = 'Doctor''s Surgery'
Unfortunately the Replace function causes an infinite loop and stack overflow, presumably because it replace function recursively converts each added quote with another 2 quotes. E.g. one quote is replaced by two, then that second quote is also replaced by two, and so on...
----------------EDIT---------------
I have noticed (thanks to posters) that the replace function used in this project is custom-written:
Public Function replace(ByVal StringToSearch As String, ByVal ToLookFor As String,
ByVal ToReplaceWith As String) As String
Dim found As Boolean
Dim position As Integer
Dim result As String
position = 0
position = InStr(StringToSearch, ToLookFor)
If position = 0 Then
found = False
replace = StringToSearch
Exit Function
Else
result = Left(StringToSearch, position - 1)
result = result & ToReplaceWith
result = result & Right(StringToSearch, Len(StringToSearch) - position - Len(ToLookFor) + 1)
result = replace(result, ToLookFor, ToReplaceWith)
End If
replace = result
End Function
Apparently, VB didn't always have a replace function of it's own. This implementation must be flawed. An going to follow folk's advice and remove it in favour of VB 6's implementation - if this doesn't work, I will write my own which works. Thanks everyone for your input!
Are you sure that it's not a proprietary implementation of the Replace function?
If so it can just be replaced by VB6's Replace.
I can't remember which version it appeared in (it wasn't in Vb3, but was in VB6) so if the original code base was vb3/4 it could be a hand coded version.
EDIT
I just saw your edit, I was Right!
Yes, you should be able to just remove that function, it'll then use the in build VB6 replace function.
We use an VB6 application that has the option of replacing ' with ` or removing them completely.
You could also walk through the letters, building a second string and inserting each ' as ''.
I just tried this in Access and it works fine (no stackoverflow):
Public Function ReplaceSingleQuote(tst As String) As String
ReplaceSingleQuote = Replace(tst, "'", "''")
End Function
Public Sub TestReplaceSingleQuote()
Debug.Print ReplaceSingleQuote("Doctor's Surgery")
End Sub

Resources