The Use of Regex.Replace with a pattern - vb.net

I have a problem with replacing a number in a string.
The code is:
Dim Searchstring As String= "2 7 12 33 4 15 22 30 15"
Dim Pattern As String= "^([0-9]$)"
Dim Match As String = Val(TextBox1.Text)
Dim ReplacementString As String = "0"
Dim rgx As Regex = New Regex(pattern)
Dim NewString As String
NewString = Regex.Replace(Searchstring, Match, ReplacementString)
RichTextBox2.Text = NewString
The problem is that when I input a number, say "2", in the textbox and run the program, the replace will be as follows in the richtextbox2.text: 0 7 10 33 4 15 00 30 15 instead of 0 7 12 33 4 15 22 30 15
But when I input the number of "22" or "12" then only these numbers will be replaced and that is okay.
So how can I find a pattern that replaces only the number "2" if I want that and only that, and not change the "12" or "22"?
Please can you help me with this case?

The appropriate pattern would be ^([0-9]+) as it would get the first digits and replace them with a 0. Actually, this '$' character represents the end of a string. If you only need to replace the first number, it shouldn't be there.
The '+' character means "One ore more from the previous pattern", then it will search for one or more digits in the "[0-9]" scope from the beginning of the text and capture only the digits.

You need to tell it how to delimit the item you want to replace, in this case the "word boundary"* entity \b will work:
Dim searchstring As String = "2 7 12 33 4 15 22 30 15"
Dim match As String = TextBox1.Text
Dim pattern = "\b" & Regex.Escape(match) & "\b"
Dim rgx As Regex = New Regex(pattern)
Dim replacementString As String = "0"
Dim newString = rgx.Replace(searchstring, replacementString)
RichTextBox2.Text = newString
I used Regex.Escape on the search term in case you want to replace something like a . or ?, which have special meanings in regular expressions; escaping them removes the special meaning and uses them as ordinary characters.
You can see that it replaces only the "2" when you enter "2" in the TextBox:
and it replaces both occurrences of "15" when you tell it to:
* What is a word boundary in regex?

To find any number in the string, you can use \b to denote the beginning or end of a word (i.e., a sequence of letters, digits and underscores).
Example: replace only the number 12:
\b12\b
This will not replace, e.g., in 123 or 412.

While I will not disagree with the answers that have been presented, I will assert that the easiest and most obvious choice would be to use built-in .NET methods to manipulate your string.
Your input is a string that contains numbers delimited by spaces. You then want to replace an exact numeric match with some replacement.
You can do this by splitting the string, looping over the array, modifying the currently iterated items that match your value, and then joining them back:
Dim searchString As String = "2 7 12 33 4 15 22 30 15"
Dim replacementString As String = "0"
If (Not Integer.TryParse(TextBox1.Text, Nothing)) Then
MessageBox.Show("Please enter a valid integer.")
Return
End If
Dim searchStringCollection() As String = searchString.Split(" "c)
For index As Integer = 0 To searchStringCollection.Length - 1
If (searchStringCollection(index) = TextBox1.Text) Then
searchStringCollection(index) = replacementString
End If
Next
Dim newString As String = String.Join(" ", searchStringCollection)
Fiddle: https://dotnetfiddle.net/dZfsy6

Related

vb.net get text between <> brackets

I am building a tool for Autodesk Inventor that works with an expression string.
=Pipe Ø<Pipe_OD> x <Pipe_t> - lg. <Pipe_length>mm
The text between <...> can be almost anything it's what the user made as input so these values are not fixed. And the number of <...> in the string can vary from 0 to 5.
What I would like to have as result for this string is following:
A converted string where the values between the <...> are replaced by number with an ascending value.
=Pipe Ø<1> x <2> - lg. <3>mm
And a string() where the values that are replaced by the numbers (above) are stored in.
I found a method that can work for strings with 1 <...> in the string but now that the quantity is variable I'm clueless about how I can do this.
Link to method
Edit: New answer with regular expressions (much better, will still have problems with additional < and > though)
Dim s As String = "abc <pipe_val1> 123 <pipe_val2> &*( <pipe_val3>k"
Dim myValues As New List(Of String)
Dim matches As MatchCollection = Regex.Matches(s, "<(.|\n)*?>", RegexOptions.IgnoreCase)
Dim totalDiff As Integer = 0
Dim idx As Integer = 0
For Each ma As Match In matches
Dim realIndex = ma.Index - totalDiff
s = s.Remove(realIndex, ma.Length).Insert(realIndex, "<" & idx.ToString & ">")
idx += 1
totalDiff += ma.Length - (idx.ToString.Count + 2)
myValues.Add(ma.Value.Trim({"<"c, ">"c}))
Next
"abc <pipe_val1> 123 <pipe_val2> &*( <pipe_val3>" will be changed to "abc <0> 123 <1> &*( <2>" and myValues will contain "pipe_val1", "pipe_val2" and "pipe_val3"

Comparing character only to character at end of string

I am writing a program in Visual Basic 2010 that lists how many times a word of each length occurs in a user-inputted string. Although most of the program is working, I have one problem:
When looping through all of the characters in the string, the program checks whether there is a next character (such that the program does not attempt to loop through characters that do not exist). For example, I use the condition:
If letter = Microsoft.VisualBasic.Right(input, 1) Then
Where letter is the character, input is the string, and Microsoft.VisualBasic.Right(input, 1) extracts the rightmost character from the string. Thus, if letter is the rightmost character, the program will cease to loop through the string.
This is where the problems comes in. Let us say the string is This sentence has five words. The rightmost character is an s, but an s is also the fourth and sixth character. That means that the first and second s will break the loop just as the others will.
My questions is whether there is a way to ensure that only the last s, or whatever character is the last one in the string can break the loop.
There are a few methods you can use for this, one as Neolisk shows; here are a couple of others:
Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"
str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace
Dim words() As String = str.ToLower.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
For Each word In words
If word.StartsWith(breakChar) Then Exit For
Console.WriteLine("M1 Word: ""{0}"" Length: {1:N0}", word, word.Length)
Next
If you need to loop though chars for whatever reason, you can use something like this:
Dim breakChar As Char = "s"
Dim str As String = "This sentence has five words"
str = str.Replace(".", " ")
str = str.Replace(",", " ")
str = str.Replace(vbTab, " ")
' other chars to replace
'method 2
Dim word As New StringBuilder
Dim words As New List(Of String)
For Each c As Char In str.ToLower.Trim
If c = " "c Then
If word.Length > 0 'support multiple white-spaces (double-space etc.)
Console.WriteLine("M2 Word: ""{0}"" Length: {1:N0}", word.ToString, word.ToString.Length)
words.Add(word.ToString)
word.Clear()
End If
Else
If word.Length = 0 And c = breakChar Then Exit For
word.Append(c)
End If
Next
If word.Length > 0 Then
words.Add(word.ToString)
Console.WriteLine("M2 Word: ""{0}"" Length: {1:N0}", word.ToString, word.ToString.Length)
End If
I wrote these specifically to break on the first letter in a word as you ask, adjust as needed.
VB.NET code to calculate how many times a word of each length occurs in a user-inputted string:
Dim sentence As String = "This sentence has five words"
Dim words() As String = sentence.Split(" ")
Dim v = From word As String In words Group By L = word.Length Into Group Order By L
Line 2 may need to be adjusted to remove punctuation characters, trim extra spaces etc.
In the above example, v(i) contains word length, and v(i).Group.Count contains how many words of this length were encountered. For debugging purposes, you also have v(i).Group, which is an array of String, containing all words belonging to this group.

Break string up

I have a string that has 2 sections broken up by a -. When I pass this value to my new page I just want the first section.
An example value would be: MS 25 - 25
I just want to show: MS 25
I am looking at IndexOf() and SubString() but I can't find how to get the start of the string and drop the end.
This might help:
http://www.homeandlearn.co.uk/net/nets7p5.html
Basically the substring method takes 2 parameters. Start position and length.
In your case, the start position is 0 and length is going to be the position found by the IndexOf method -1.
For example:
Dim s as String
Dim result as String
s = "MS 25 - 25"
result = s.SubString(0, s.IndexOf("-")-1)
You could use the Split function on the hyphen.
.Split("-")
If you want to stay away from Split, you could use SubString
yourString.Substring(0, yourString.IndexOf("-") - 1)
EDIT
The above code will fail in the instances where there is no hyphen at all or the hyphen is in the beginning of the string, also when there are no spaces surrounding the hyphen, the full leading substring will not be returned. Consider using this for safety:
Dim pos As Integer
Dim result As String
pos = yourString.IndexOf("-")
If (pos > 0) Then
result = yourString.Substring(0, pos)
ElseIf (pos = 0) Then
result = String.Empty
Else
result = yourString
End If

Display first and last half of any string entered into textbox

I want to display the first and last characters of any given string entered into a textbox. The strings can be of any length as the user wants (as long as it is one word) I would like to be able to do something like this... "william = will and iam" or "Celtic = Cel and tic"
I understand I would have to split or divide the string. How would I go about doing this? Any help is appreciated, thanks.
EDIT:
Thanks for your help once again guys, this is how the code ended up!
Dim strInput = txtString.Text
Dim halflength = strInput.Length / 2
Dim firsthalf = strInput.Substring(0, halflength)
Dim secondhalf = strInput.Substring(halflength)
Dim strResults = firsthalf
Dim secondResult = secondhalf
MessageBox.Show(firsthalf)
MessageBox.Show(secondhalf)
MessageBox.Show("First half of string contains... " & " " & strResults.Length.ToString & " characters", "Character Count")
MessageBox.Show("Second half of string contains... " & " " & secondResult.Length.ToString & " characters", "Character Count")
EDIT:
Also meant to mention my current incorrect code.
Dim strInput As String
Dim strLength As String
Dim strResults As String
strInput = txtString.Text
strLength = strInput.Length / 2
strResults = txtString.Text
MessageBox.Show(strInput.Length.ToString, "Length of characters")
MessageBox.Show(strLength.ToString)
MessageBox.Show(strResults.Substring(0, 3))
String.Substring and String.Length should give you everything you need to get started on this.
Seeing your existing code will make this easier. Let's walk through what we have now.
Let's assume we have just a plain, simple string like this instead of a textbox for the sake of making things easier:
Dim txtString = "Hello World"
Now, in order to split the length of the string in half; we need to get the length. The `Length property will give is that, and then divide it by two.
Dim halfLength = txtString.Length \ 2
This will perform integer division; so any remaining decimal is truncated.
Now we know where the middle of the string is. We can now use String.Substring to carve out a peice of the string by index. Substring takes two parameters, the index where to start the string, and number of characters to take. There is a second overload that takes the index to start at and consumes till the end of the string. Indexes are zero based. So for example, if we wanted to start at the beginning of the string, we'd use zero. If we wanted to skip the first character, we'd use one.
For the first half of the string, we don't want to skip any characters, so we'll use zero. The number of characters we want is half length of the string, so we pass in halfLength:
Dim firstHalf = txtString.Substring(0, halfLength)
For the second half, we want to start in the middle of the string, and consume characters till the end, so we'll use the other overload:
Dim secondHalf = txtString.Substring(halfLength)
You now have your string split in half.
The final result looks like this:
Dim txtString = "Hello World"
Dim halfLength = txtString.Length \ 2
Dim firstHalf = txtString.Substring(0, halfLength)
Dim secondHalf = txtString.Substring(halfLength)
Assuming the rules are "each side is half the length with the left side taking precedence", you would use Substring and some simple division:
Dim str As String = "william"
Dim part1 As String = str.Substring(0, CInt(Math.Ceiling(str.Length / 2.0#)))
Dim part2 As String = str.Substring(part1.Length)
part1 & " and " & part2 'will and iam
Here's a demo.
My code displays first half and last half of any number of characters entered.
Declare Variable
Dim strResults As String
Fetch text from textbox
strResults = Textbox1.Text
Display the first half of the text
MessageBox.Show(strResults.Substring(0, strResults.Length / 2), "First Half Characters")
Display the last half of the text
MessageBox.Show(strResults.Substring(strResults.Length / 2), "Last Half Characters")
Full code:
Dim strResults As String
strResults = Textbox1.Text
MessageBox.Show(strResults.Substring(0, strResults.Length / 2), "First Half Characters")
MessageBox.Show(strResults.Substring(strResults.Length / 2), "Last Half Characters")

How can I cut the string into pieces and then stored them in array

In my website I have a textbox that allow user to enter a group of numbers like this:
(118,38,137,15,156,14,157,36,152,49,142,57)
How can I store these numbers in an array like the following?:
[118 38 137 15 156 14 157 36 152 49 142 57]
Use the Split method:
yourString = yourString.Substring(1, yourString.Length - 2) ' Trim parentheses.
Dim result As String() = yourString.Split(","c)
The Split method has several overloads, depending on purpose. I’ve chosen the simplest here, that only takes a single Character argument, in this case ","c, a comma.
You can use regular expressions:
Dim str As string = "(118,38,137,15,156,14,157,36,152,49,142,57)"
Dim matches As MatchCollection = New Regex(#"\d+").Matches(str)
Dim ints As Integer() = New Integer(matches.Count - 1) }
Dim i as Integer
For i = 0 To ints.Length - 1
ints[i] = int.Parse(If(matches.Item(i).Value <> Nothing, _
a.Item(i).Value, "").ToString())
Next
See String.Split
myArray = "118,38,137,15,156,14,157,36,152,49,142,57".Split (",")