How to match a simple number pattern in VBA using RegEx [closed] - regex

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
How do I check if a string is either a one digit number OR a two digit number and otherwise return false?

How about:
Function OneOrTwo(i As Integer) As Boolean
Dim objRegEx As Object
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.Pattern = "^\d{1,2}$"
OneOrTwo = objRegEx.Test(i)
End Function
See: http://msdn.microsoft.com/en-us/library/ms974570.aspx

You can also do this using VBA LIKE:
Function OneOrTwo(Digits As Variant) As Boolean
OneOrTwo = Digits Like "#" Or Digits Like "##"
End Function

IF CInt(myNumberString) < 100 Then
MsgBox "String must be either 1 or 2 digits"
Else
Msgbox "Failed"
End IF
Should work for you.

Remou had it right. Here is a RegexContains function so you can use it with all sorts of patterns, not just the one you need now.
Function RegexContains(ByVal find_in As String, _
ByVal find_what As String, _
Optional IgnoreCase As Boolean = False) As Boolean
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = find_what
RE.IgnoreCase = IgnoreCase
RE.Global = True
RegexContains = RE.Test(find_in)
End Function
Following the example from Remou, assuming the cell is A1, you'd write:
=RegexContains(A1, "^\d{1,2}$")

Here is what I would try. /d for digit, ? for option 2 digits.
/d/d?
or
/d{1,2}

Related

Replacement in excel sheet by list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to make bulk replacement using regexp patterns from excel range, see my answer below:
Here is my way to make replacement in Excel range using list from another range based on RegExp:
Sub regexpreplace()
Set Myrange = ActiveSheet.Range("A2:A1000") 'range in which we make replace
Set regrange = ActiveSheet.Range("B2:B6") 'range with RegExp pattern
'in range C1:C6 we have pattern for replace
For Each D In regrange
For Each C In Myrange
Set rgx = CreateObject("VBScript.RegExp")
rgx.IgnoreCase = True
rgx.Pattern = D.Value
rgx.Global = True
C.Value = rgx.Replace(C.Value, D.Offset(0, 1).Value)
Next
Next
End Sub
In this code:
A1:A1000 - range with input values
B1:B6 - list of RegExp patterns
C1:C6 - list of output patterns
Some examples of using script:

VB.Net find the word in textbox and counting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to find the specific word in the textbox, and I want to count it.
For example,
There is TextBox which contains "abababababab" (6 ab)
and there is another textbox wich contains "ab"
And I want to get the result : 6.
How can I do it?
You can do it like this:
Dim text As String = "abababababab"
Dim find As String = "ab"
Dim result As Integer = CInt((text.Length - text.Replace(find, "").Length) / find.Length)
also this way :
Imports System.Text.RegularExpressions
+++++++
Dim txt As String
txt = "abababababab"
Dim count As Integer
count = Regex.Matches(txt, Regex.Escape("ab")).Count()
Replace the matching chars in the first string with empty strings, then subtract from the lenght of the original string the length of the resulting string, finally divide by the lenght of the matching string
Dim test = "abababababab"
Dim result = test.Replace("ab", "")
Dim len = (test.Length - result.Length) / "ab".Length
Console.WriteLine(len)

Remove non-numeric characters from a range of cells [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a 1500 row excel file.
In the first column I have characters mixed up with numbers (every row is different).
I would like to leave only the numbers and delete the alpha characters.
For example in A1 I have
f90f5j49,35.48
and after I delete the alpha characters it should be
905493548
What is the best way to do this?
I did find this youtube solution
Thanks!
Your method is the right approach.
The quickest way to implement this is to use
a regexp
and a variant array in VBA.
Using code based on my Article Using Variant Arrays in Excel VBA for Large Scale Data Manipulation
Sub KillNonNumbers()
Dim rng1 As Range
Dim rngArea As Range
Dim lngRow As Long
Dim lngCol As Long
Dim lngCalc As Long
Dim objReg As Object
Dim X()
On Error Resume Next
Set rng1 = Application.InputBox("Select range for the replacement of non-number", "User select", Selection.Address, , , , , 8)
If rng1 Is Nothing Then Exit Sub
On Error GoTo 0
'See Patrick Matthews excellent article on using Regular Expressions with VBA
Set objReg = CreateObject("vbscript.regexp")
objReg.Pattern = "[^\d]+"
objReg.Global = True
'Speed up the code by turning off screenupdating and setting calculation to manual
'Disable any code events that may occur when writing to cells
With Application
lngCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
End With
'Test each area in the user selected range
'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
For Each rngArea In rng1.Areas
'The most common outcome is used for the True outcome to optimise code speed
If rngArea.Cells.Count > 1 Then
'If there is more than once cell then set the variant array to the dimensions of the range area
'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
X = rngArea.Value2
For lngRow = 1 To rngArea.Rows.Count
For lngCol = 1 To rngArea.Columns.Count
'replace the leading zeroes
X(lngRow, lngCol) = objReg.Replace(X(lngRow, lngCol), vbNullString)
Next lngCol
Next lngRow
'Dump the updated array sans leading zeroes back over the initial range
rngArea.Value2 = X
Else
'caters for a single cell range area. No variant array required
rngArea.Value = objReg.Replace(rngArea.Value, vbNullString)
End If
Next rngArea
'cleanup the Application settings
With Application
.ScreenUpdating = True
.Calculation = lngCalc
.EnableEvents = True
End With
Set objReg = Nothing
End Sub

vbscript function clean string only allow certain characters

Until now I've been manually adding characters to replace that break my code. I'd like to be a bit more proactive, so I found this function that is supposed to replace everything EXCEPT valid characters. My first hurdle is that it doesn't seem to work. The code below is my full test file and the MsgBox comes up blank.
My second question is about performance. This function handles very, very large strings. Will this method be considerably slower? Anyone recommend anything else?
Function CleanUp (input)
Dim objRegExp, outputStr
Set objRegExp = New Regexp
objRegExp.IgnoreCase = True
objRegExp.Global = True
objRegExp.Pattern = "((?![a-zA-Z0-9]).)+"
outputStr = objRegExp.Replace(input, "-")
objRegExp.Pattern = "\-+"
outputStr = objRegExp.Replace(outputStr, "-")
CleanUp = outputStr
End Function
MsgBox (CleanUp("Test"))
Edit: I'm stupid and just saw the variable mixup I did which was causing it to return nothing. It is working now. Will still accept input for performance question or better suggestions.
You can simplify it even further.
objRegExp.Pattern = "[^\w+]"
It don't know what is the expected result for your example, but maybe you can try that for the pattern instead:
objRegExp.Pattern = "[^a-zA-Z0-9]"
Hope it works

Regular expression substring replacement in Microsoft Excel [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I would like to bulk replace the "07" part of a list of strings (mobile telephone numbers) with the international version "447".
The list of strings currently forms a columnn in an Excel spreadsheet.
I have the regular expression to match strings requiring modification:
^07[0-9]{9}$
...but I don't know how to do the replacement that I need.
The data is in an Excel spreadsheet, but can of course be exported.
Preferred solution would be to keep the data in Microsoft Excel, but it can of course be exported and then re-imported. I know TextMate has a regular expression replace feature. Can this help me?
I was about to go off looking for elegant VBA solutions or whatever, then I thought: 'Hang on. We just want to manipulate some data in a spreadsheet we own. Why complicate things?'
How does this idea sound to you:
insert a new column just after the column with the existing data (let's assume that is column C)
fill the new column with this formula: ="447" & RIGHT(C1, 9)
select column D (which now contains the new values) and Paste Values (which is in the Paste Special dialog) onto column C, replacing existing values
delete the 'working' column D
It's not programming but if you only have to do it once you don't need a program, right?
Use Excel VBA. Make a reference to "Microsoft VBScript Regular Expressions 5.5".
Then do, in a new regular VBA module:
Sub ReplaceMobileNumbers
Dim re as New RegExp
re.Pattern = "^0(?=7[0-9]{9}$)" ''# look-ahead
Dim cell As Range
For Each cell In ActiveSheet.Range("Your Range Address in A1:B1 notation")
cell.Value = re.Replace(cell.value, "44")
Next cell
End Sub
and call this sub in the Immediate Window. The above is throw-away code, not designed with re-usability in mind. I know that, so don't tell me. ;-)
Though you can probably get away with a cell function:
=IF(AND(LEN(A1) = 11;LEFT(A1; 2) = "07"); "44" & RIGHT(A1; 10); A1)
You'll have to include Microsoft Regular Expressions in your sheet (add it as a Reference)
Then make a quick macro, like the following, to use it:
Dim reg As New RegExp
Public Function RegMatch(Source As Range, Pattern As String, Optional IgnoreCase As Boolean = True, Optional MultiLine As Boolean = True) As Long
Dim rng As Range, i As Long, j As Long
reg.IgnoreCase = IgnoreCase
reg.MultiLine = MultiLine
reg.Pattern = Pattern
i = 0: j = 0
For Each rng In Source
i = i + 1
If reg.test(rng.Value) Then
j = i
Exit For
End If
Next
RegMatch = j
End Function
Then, simply call it as a macro in your sheet (for example):
=INDEX(B6:B15, RegMatch($A$6:$A$15, $A$3))
Where the first argument is your range, and the second argument is your pattern (as above)