VB.NET Get text in between multiple Quotations - vb.net

i need some help.
i need to get there text file value on Quot ("") on multi textbox1, textbox2, textbox3. but can only get on value (first value on textbox1)
now a time i just get one value (firt value on Quot)
text file (2.txt):
C:\contexture\img2itp.exe "\mynetwork\1.png" "\mynetwork\2.png" "148"
code vb:
Using sr As New StreamReader("C:\test\2.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadToEnd()
Dim s As String = line
Dim i As Integer = s.IndexOf("""")
Dim f As String = s.Substring(i + 1, s.IndexOf("""", i + 1) - i - 1)
TextBox1.Text = f
thanks for a help :)

Regex Match
What Is Regex :
A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.
Source: https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
Here we could consider two Regex Expressions to solve this problem a simple version and a more complex creating capture groups.
Simple one :
"(.*?)"
Here is the explanation: https://regex101.com/r/mzSmH5/1
Complex One :
(["'])(?:(?=(\\?))\2.)*?\1"(.*?)"
Here is an explanation: https://regex101.com/r/7ZMVsB/1
VB.NET Implementation
This would be a job for a Regex.Matches which would work like this:
Dim value As String = IO.File.ReadAllText("C:\test\2.txt")
Dim matches As MatchCollection = Regex.Matches(value, """(.*?)""")
' Loop over matches.
For Each m As Match In matches
' Loop over captures.
For Each c As Capture In m.Captures
' Display.
Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value)
Next
Next

Related

Change a string and insert characters in between

I have this string: 71892378917238978
I want to do this: 71892-37891723-8978
I was trying this, but how i can do it multiple times?
String.Insert(6, "-")
We could start with this idea. Create an array of the substrings that you want to exist between the dash symbol. In your expected string you have 71892-37891723-8978, so the first block is composed of 5 char and the second block is 8 char.
Using the string.Substring method we could extract these substrings parts and store them in an array. Finally we could use string.Join to rebuild the string with the expected separator
Dim s As String = "71892378917238978"
' Define the substring blocks
Dim blocks As Integer() = New Integer() {5,8}
' Define the array that will contain the substrings
Dim substrings(blocks.Length) As String
' Get the blocks
For x As Integer = 0 To blocks.Length - 1
substrings(x) = s.Substring(0,blocks(x))
s = s.Substring(blocks(x))
Next
' Join together with the last part not included in the substrings
Dim result = String.Join("-", substrings) & s
Console.WriteLine(result)
You could generalize this code putting everything in a method where you could pass the string, the blocks and the separator.

search for phrase in line of text box vb.net

I'm using VB.NET and I've got a text box which contains the following information (that changes depending on the video file selected in a list box):-
type: ffmpeg-producer
filename: C:\caspar\Server\media\\adi.divx
width: 640
height: 360
progressive: false
fps: 25
loop: false
frame-number: 0
nb-frames: 4626
file-frame-number: 0
file-nb-frames: 4626
When I click a button, I need to add the data to a variable. So for example, I would need to take 4626 from the line
nb-frames: 4626
and 25 from the
line fps:25
and put them both in variables to then calculate the actual duration.
Public Function GetValue(ByVal varName As String) As String
Dim lines() As String = Split(TextBox1.Text, Delimiter:=Environment.NewLine)
For Each line As String In lines
Dim words() As String = Split(line, Delimiter:=": ", Limit:=2)
If words(0) = varName And words.Length = 2 Then
Return words(1)
End If
Next
Return Nothing
End Function
You could also use a regular expression approach. If you you are not familiar with regular expressions I strongly encourage you to into it.
Here is what you would do (where txtMyTextbbox is the textbox, that holds your data:
Dim strRegex as String = "([\w-]*):\s*(.*)"
Dim myRegex As New Regex(strRegex, RegexOptions.None)
Dim strTargetString As String = txtMyTextbox.Text
For Each myMatch As Match In myRegex.Matches(strTargetString)
If myMatch.Success Then
dim category = myMatch.Groups(1).Value
dim value = myMatch.Groups(2).Value
End If
Next
This code loops through all matches in your textbox text and looks for a text followed by a colon followed by spaces and the rest of the line. Each match is captured in the myMatch variable where you can access the part before the colon through myMatch.Groups(1).value and the part after the colon (excluding the space) through the second group.
Leave a comment if you have further questions.

String.replace adding extra characters

I am trying to replace some words in mails in Outlook. Here is my code for it
Dim input As String = mail.HTMLBody
Dim pattern As String = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]"
Dim replacement As String
Dim rgx As New Regex(pattern)
Dim match As Match = Regex.Match(input, pattern)
While (match.Success)
replacement = "A" + match.Value + "A"
input = input.Replace(match.value, replacement)
match = match.NextMatch()
End While
mail.HTMLBody = input
For this input
QWQrt12345
QWQrt1234533
wwQWQrt12345
QWQrt1234534
qwwQWQrt12345
I expect output as
AQWQrt12345A
AQWQrt12345A33
wwAQWQrt12345A
AQWQrt12345A34
qwwAQWQrt12345A
But the output I am getting is
AAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA33
wwAAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA34
qwwAAAAAQWQrt12345AAAAA
What can be the issue?
The description of String.Replace states,
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
The important takeaway there is, "all occurrences ... are replaced." Since your replacement string is also a match for your regular expression pattern, it will be replaced (thus adding another set of 'A') upon every iteration.
Try a test case using something like this, instead:
replacement = match.Value.Replace("Q", "A")
The details here don't matter (you can change whatever you want), the point is that you change something so that your strings aren't matched repeatedly.
simply put your adding 'A' + match + 'A' evertytime you match .
Resulting in the AAAAA before and after your input. I've been voted down?
ok I explain your first match input result is exactly what you have inputted(all characters could be matched), you then add "A" both sides and want to replace your replaced value with the original value.
Here's the c# code to get expected value :
var input = "QWQrt1234533"; //your second line example
const string pattern = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]";
var rgx = new Regex(pattern);
Match match = Regex.Match(input, pattern);
while (match.Success)
{
var replacement= "A" + match.Value + "A";
input = input.Replace(match.Value, replacement);
match = match.NextMatch();
}
Console.Write(input);
resulting in your exected : "AQWQrt12345A33"
not getting your results even with the posted VB code (you did not edit the original after my first response?)

Splitting string in VB.NET produces unusual results

I am using the Split function in VB.NET, and it is producing a weird result when I display the output.
I have an XML document, and I just want to loop through each <backup> tag in the document, so I am using:
Dim XMLString As String
XMLString = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim SplitBackup As String()
SplitBackup = XMLString.Split("<backup>")
For Each BackupContent In SplitBackup
MsgBox(BackupContent)
Next
Now, one would expect this to output INFO in a MsgBox, I click OK and then another one would popup and show 'ANOTHER INFO', but it seems that the Split function is getting stuffed up with the '<' and '>' in it. Is there someway I can get around this by escaping it, or parsing it some other way.
Any suggestions are much appreciated!
Give XML a chance.
Dim bups As XElement = <backups><backup>INFO</backup><backup>ANOTHER INFO</backup></backups>
For Each xe As XElement In bups.Elements
Debug.WriteLine(xe.Value)
Next
One possibility to do this is to use regular expression to split the tags (and escape the problematic symbols) and then use LINQ to Objects to get the value from each tag:
Dim XMLString As String = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim words = Regex.Split(XmlString, "\<backup\>").Where(function(f) not String.IsNullOrEmpty(f)).Select(function(f) f.Replace("</backup>", String.Empty)) '
for each word in words
Console.WriteLine(word)
next word
The output is:
INFO
ANOTHER INFO
What the code does:
Dim words = Regex
' split on every tag
.Split(XmlString, "\<backup\>")
' remove empty items
.Where(function(f) not String.IsNullOrEmpty(f))
' remove trailing closing tag and thus retrieve the value within
.Select(function(f) f.Replace("</backup>", String.Empty))
As already suggested you better learn how to use the build-in XML support - it is easier and safer because you do not need to pay attention to the brackets - < and > are automatically handled. A possible solution could look like this (! you need to have a valid XML structure - one unique root node!):
' !!! you need to have a valid XML element - one root node !!!
Dim XMLString As String = "<root><backup>INFO</backup><backup>ANOTHER INFO</backup></root>"
dim words = XDocument.Parse(XMLString).Root.Descendants("backup").Select(function (f) f.Value)
for each word in words
Console.WriteLine(word)
next word
The output is the same as above. How does the code work:
dim words = XDocument
' parse the specified XML structure; use Load("file.xml") to load from file
.Parse(XMLString)
' from the root node
.Root
' take all nodes matching the specified tag
' note - no need to pay attention to the < and >
.Descendants("backup")
' select the value of the XML node
.Select(function (f) f.Value)
You would need to get rid of the close element.
So you could use:
Dim XMLString As String
XMLString = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim SplitBackup As String()
SplitBackup = XMLString.Split("<backup>")
For Each BackupContent In SplitBackup
Dim Something() as string
Something = BackupContent.Split("</backup">)
MsgBox(Something(0))
Next
Not the most elegant coding though.

Lowercase the first word

Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.