VB .net 2010 - Get Substring of String in quote - string

I have a file which contains some lines. I managed to find all lines in a Loop. The lines I need look like this: (PS: I thinnk there can be used regex for this..)
if "%testfile%"=="abcd" (
This file contains more of this lines but the abcd changes to whatever. Also there could be different blanks like
if "%testfile%" =="abcd" (
etc.
I want to get
abcd
in a variable inside my Loop that I can use it further.
Following part is doing it: ( lineArray.Item(x) contains the whole line )
For x = 0 To lineArray.Count - 1
If lineArray.Item(x).Contains("%testfile%") Then
MsgBox(lineArray.Item(x)) 'here should it be done.
End If
Next

You are absolutely right, this can be done with a regex. I suggest this pattern:
(?<=if\s+"%testfile%"\s*==\s*)".*?"(?=\s+\()
Online Demo
Explanation
(?<=if\s+"%testfile%"\s*==\s*) lookbehind to asert line in question with extra + / optiona * whitespace \s
".*?" layz match the target string
(?=\s+\() lookahed as rear anchor
Code Sample:
Imports System
Imports System.Text.RegularExpressions
Public Class Example
Public Shared Sub Main()
Dim pattern As String = "(?<=if\s+""%testfile%""\s*==\s*)"".*""(?=\s+\()"
Dim input As String = "if ""%testfile%"" ==""abcd"" ( "
Dim options As RegexOptions = RegexOptions.Multiline
For Each m As Match In Regex.Matches(input, pattern, options)
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index)
Next
End Sub
End Class

Related

Excel VBA: How to write column name with commercial at "#" in it

I am trying to find out how I should deal with a named column in myTable which contains a commercial at (#) in its name, e.g. active # mail. This code is supposed to print the column number in the Immediate output window:
Sub teststring()
Dim s As String
s = ActiveSheet.Range("myTable[active # mail]").Column
Debug.Print s
End Sub
but it fails. Using .Range("myTable[active" & Chr(64) "& mail]") fails as well.
You can do it like this:
s = ActiveSheet.listobjects("myTable").listcolumns("active # mail").Range.Column
See also https://support.office.com/en-us/article/using-structured-references-with-excel-tables-f5ed2452-2337-4f71-bed3-c8ae6d2b276e for how to escape special characters
So:
s = ActiveSheet.Range("myTable[active '# mail]").Column
will also work.
# has a special meaning in structured references, so you can't use it in a column name without escaping it with ' (a single quote)

How do I extract a series of numbers along with a single letter followed by another series of numbers?

The problem that I'm facing is that I have an entire column that has text separated by _ that contains pixel size that I want to be able to extract but currently can't. For example:
A
Example_Number_320x50_fifty_five
Example_Number_One_300x250_hundred
Example_Number_two_fifty_728x49
I have tried using Substitute function to grab the numbers which works but only grabs the numbers when I need something like: 320x50 instead I'm getting 0, as I'm not sure how to exactly extract something like this. If it was consistent I could easily do LEFT or RIGHT formula's to grab it but as you can see the data varies.
The result that I'm looking for is something along the lines of:
A | B
Example_Number_320x50_fifty_five | 320x50
Example_Number_One_300x250_hundred | 300x200
Example_Number_two_fifty_728x49 | 728x49
Any help would be much appreciated! If any further clarification is needed please let me know and I'll try to explain as best as I can!
-Maykid
I would probably use a Regular Expressions UDF to accomplish this.
First, open up the VBE by pressing Alt + F11.
Right-Click on VBAProject > Insert > Module
Then you can paste the following code in your module:
Option Explicit
Public Function getPixelDim(RawTextValue As String) As String
With CreateObject("VBScript.RegExp")
.Pattern = "\d+x\d+"
If .Test(RawTextValue) Then
getPixelDim = .Execute(RawTextValue)(0)
End If
End With
End Function
Back to your worksheet, you would use the following formula:
=getPixelDim(A1)
Looking at the pattern \d+x\d+, an escaped d (\d) refers to any digit, a + means one or more of \d, and the x is just a literal letter x. This is the pattern you want to capture as your function's return value.
Gosh, K Davis was just so fast! Here's an alternate method with similar concept.
Create a module and create a user defined function like so.
Public Function GetPixels(mycell As Range) As String
Dim Splitter As Variant
Dim ReturnValue As String
Splitter = Split(mycell.Text, "_")
For i = 0 To UBound(Splitter)
If IsNumeric(Mid(Splitter(i), 1, 1)) Then
ReturnValue = Splitter(i)
Exit For
End If
Next
GetPixels = ReturnValue
End Function
In your excel sheet, type in B1 the formula =GetPixels(A1) and you will get 320x50.
How do you create a user defined function?
Developer tab
Use this URL to add Developer tab if you don't have it: https://www.addintools.com/documents/excel/how-to-add-developer-tab.html
Click on the highlighted areas to get to Visual Basic for Applications (VBA) window.
Create module
Click Insert > Module and then type in the code.
Use the user defined function
Note how the user defined function is called.

Multiple space delimiter split string

I have a string like
string = "computer prog <5spaces> data mining <5spaces> oops concept"
As we can see clearly computer prog, data mining etc., are one continuous string and the delimiter is 5 spaces between the strings " ".
I need to split based on this in vb.net - so far I tried regex.split which works but results in giving 2 empty strings additionally and it's tedious to remove those additional strings.
I also tried using the string.split method but again it's taking even single white space also delimiters.
Below are the tried options:
regex.split
string.split
None give me the required result. I am not sure what I need to use. I even tried the option of stringsplitoption.removesapceentry (something like that) to get the desired result inside the split method, but none worked.
Dim array_keyskills As String() = res.Split(" ".ToCharArray,StringSplitOptions.RemoveEmptyEntries)
system.Windows.MessageBox.Show(array_keyskills(2) & array_keyskills.Length & " key skills") 'Display
The following short program:
Module Module1
Sub Main()
Dim s = "computer prog data mining oops concept"
Dim parts = s.Split({" "}, StringSplitOptions.None)
For Each p In parts
Console.WriteLine(p)
Next
Console.ReadLine()
End Sub
End Module
outputs:
computer prog
data mining
oops concept
If your data does not work that way then you should examine it to find which whitespace characters are in it which appear to be spaces but are not.
This did the trick:
array_keyskills = System.Text.RegularExpressions.Regex.Split(res," ").Where(
Function(s) Not String.IsNullOrWhitespace(s)
).ToArray()

Parsing name/value pairs containing spaces delimited by spaces

I'm trying to parse a file in vb.net. This file is the output of a CLI command on Mikrotik RouterOS.
The file looks like this, where the \ and the end of the line means the line continues below
# jan/03/2017 12:46:35 by RouterOS 6.38
# software id = 3BQ2-2I1I
#
/queue simple
add dst=WAN max-limit=5M/20M name=Compartido01 priority=1/1 queue=\
wireless-default/wireless-default target="" total-priority=1
add max-limit=512k/2M name="6206101450 - Simone Walter (2M) (P13)" parent=\
Compartido01 target=190.211.88.1/32
add max-limit=350k/1M name=\
"6206130537 - Figueroa Viviana del Carmen (1M) (P14)" parent=Compartido01 \
target=190.211.88.24/32
I managed to skip the 4 first lines and collapse them so they look like this
"add dst=WAN max-limit=5M/20M name=Compartido01 priority=1/1 queue=wireless-default/wireless-default target="" total-priority=1"
"add max-limit=512k/2M name="6206101450 - Simone Walter (2M) (P13)" parent=Compartido01 target=190.211.88.1/32"
"add max-limit=350k/1M name="6206130537 - Figueroa Viviana del Carmen (1M) (P14)" parent=Compartido01 target=190.211.88.24/32"
What I need to do is to extract the information on those strings, something like "name=XXXXXX" and "target=XXXXX"
I could split using space as delimiter but the "name" field can have spaces inside it
Anyone can give me a hint ?
What you need is a RegEx match parser...Found one here. See if you can make what you need from this.
Imports System.Text.RegularExpressions
Module Parser
Public Function ParseKeyValuePairs(ByVal Buffer As String) As Dictionary(Of String, String)
Dim Result = New Dictionary(Of String, String)
'---- There are 3 sub patterns contained here, seperated at the | characters
' The first retrieves name="value", honoring doubled inner quotes
' The second retrieves name=value where value can't contain spaces
' The third retrieves name alone, where there is no "=value" part (ie a "flag" key
' where simply its existance has meaning
Dim Pattern = "(?:(?<key>[\w-]+)\s*\=\s*""(?<value>[^""]*(?:""""[^""]*)*)"") | " & _
"(?:(?<key>[\w-]+)\s*\=\s*(?<value>[^""\s]*)) | " & _
"(?:(?<key>[\w-]+)\s*)"
Dim r = New System.Text.RegularExpressions.Regex(Pattern, RegexOptions.IgnorePatternWhitespace)
'---- parse the matches
Dim m As System.Text.RegularExpressions.MatchCollection = r.Matches(Buffer)
'---- break the matches up into Key value pairs in the return dictionary
For Each Match As System.Text.RegularExpressions.Match In m
Result.Add(Match.Groups("key").Value, Match.Groups("value").Value)
Next
Return Result
End Function
Public Sub Main()
Dim s = "Key1=Value Key2=""My Value here"" Key3=Test Key4 Key5"
Dim r = ParseKeyValuePairs(s)
For Each i In r
Debug.Print(i.Key & "=" & i.Value)
Next
End Sub
End Module

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