Visual Basic 2013 RegEx - regex

How can I get only the Name?
"Hello Name!"
Dim r As New Regex("Hello (.*)! :)")
Dim matches As MatchCollection = r.Matches(Chat)
For Each m As Match In matches
MsgBox("Hi " & m.ToString & " and welcome back!")
Next
(Chat is the last Chatmessage)

To get only name, you should use Groups. And if you really want to match :), you must escape ) by using \:
Dim Chat As String = "Hello Name!"
Dim r As New Regex("Hello (.*)! :\)")
Dim matches As MatchCollection = r.Matches(Chat)
For Each m As Match In matches
m.Groups(1).Value
Next

Why don't you do a string replace for Hello and the ! as you know these are fixed??
I don't know VB, but a REGEX in other language should be Hello (\S+)!

Related

Replace part of String, using regex and vb.net

My application stores the path of the userdata.dll in a String.
I need to convert this string: C:\Applications\User\userdata.dll
into this: C:\\Applications\\User\\userdata.dll
All \ will need to be duplicated, independent on how many \ the path have.
Something like:
Dim defaultPath As String = "C:\Applications\User\userdata.dll"
' Regex
Dim r As Regex = New Regex( ... )
' This is the replacement string
Dim Replacement As String = " ... $1 ... "
' Replace the matched text in the InputText using the replacement pattern
Dim modifiedPath As String = r.Replace(defaultPath,Replacement)
Any help on this? I am trying to follow this question:
How to replace some part of this string with vb.net?
But cant find out how to make this Regex...
You can use
Dim pattern As String = "\\"
Dim rgx As New Regex(pattern)
Dim input As String = "C:\Applications\User\userdata.dll"
Dim result As String = rgx.Replace(input, "\\")
Console.WriteLine(result)
Ideone Demo
If you mean to say that replace any number of \ to \\, then you can use
Dim pattern As String = "\\+"
Dim rgx As New Regex(pattern)
Dim input As String = "C:\\\\Applications\User\userdata.dll"
Dim result As String = rgx.Replace(input, "\\")
Ideone Demo

regex with XE currency

guys I'm trying to make my personal app with VB.Net
and all of my code is working fine except one thing, which is the regex
I want to get this value
The Highlighted Value that I need
From this URL
I tried this regex:
("([0-9]+.+[1-9]+ (SAR)+)")
and it's not working very well (only works with some currency but not all).
so guys can you help with the perfect regex ?
***Update:
here is the whole function code:
Private Sub doCalculate()
' Need the scraping
Dim Str As System.IO.Stream
Dim srRead As System.IO.StreamReader
Dim strAmount As String
strAmount = currencyAmount.Text
' Get values from the textboxes
Dim strFrom() As String = Split(currecnyFrom.Text, " - ")
Dim strTo() As String = Split(currecnyTo.Text, " - ")
' Web fetching variables
Dim req As System.Net.WebRequest = System.Net.WebRequest.Create("https://www.xe.com/currencyconverter/convert.cgi?template=pca-new&Amount=" + strAmount + "&From=" + strFrom(1) + "&To=" + strTo(1) + "&image.x=39&image.y=9")
Dim resp As System.Net.WebResponse = req.GetResponse
Str = resp.GetResponseStream
srRead = New System.IO.StreamReader(Str)
' Match the response
Try
Dim myMatches As MatchCollection
Dim myRegExp As New Regex("(\d+\.\d+ SAR)")
myMatches = myRegExp.Matches(srRead.ReadToEnd)
' Search for all the words in the string
Dim sucessfulMatch As Match
For Each sucessfulMatch In myMatches
mainText.Text = sucessfulMatch.Value
Next
Catch ex As Exception
mainText.Text = "Unable to connect to XE"
Finally
' Close the streams
srRead.close()
Str.Close()
End Try
convertToLabel.Text = strAmount + " " + strFrom(0) + " Converts To: "
End Sub
Thanks.
You need to get the currency value that appears first. Thus, you need to replace
myMatches = myRegExp.Matches(srRead.ReadToEnd)
' Search for all the words in the string
Dim sucessfulMatch As Match
For Each sucessfulMatch In myMatches
mainText.Text = sucessfulMatch.Value
Next
with the following lines:
Dim myMatch As Match = myRegExp.Match(srRead.ReadToEnd)
mainText.Text = myMatch.Value
I also recommend using the following regex:
\b\d+\.\d+\p{Zs}+SAR\b
Explanation:
\b - word boundary
\d+ - 1+ digits
\. - a literal dot
\d+ - 1+ digits
\p{Zs}+ - 1 or more horizontal whitespace
SAR\b - whole word SAR.
You should use this regex.
Regex: (\d+\.\d+ SAR)
Explanation:
\d+ looks for multiple digits.
\.\d+ looks for decimal digits.
SAR matches literal string SAR which is your currency unit.
Regex101 Demo
I tried this regex:
("([0-9]+.+[1-9]+ (SAR)+)") and it's not working very well (only works
with some currency but not all).
What you are doing here is matching multiple digits anything multiple digits SAR multiple times.

Finding the first occurrence of a regex match using match.index

How do I access the .index method in regex, so in this case it should output the location of the first instance of a number
Dim sourceString As String = "abcdefg12345"
Dim textboxregex As Regex = New Regex("^(d)$")
If textboxregex.IsMatch(sourceString) Then
Console.WriteLine(Match.Index) 'this should display the location of the first occurrence of the pattern within the sourcestring
End If
In this case you dont need regex:
Dim digits = From chr In sourceString Where Char.IsDigit(chr)
Dim index = -1
If digits.Any() Then index = sourceString.IndexOf(digits.First())
or in one statement with the ugly method syntax:
Dim index As Int32 = "abcdefg12345".
Select(Function(chr, ix) New With {chr, ix}).
Where(Function(x) Char.IsDigit(x.chr)).
Select(Function(x) x.ix).
DefaultIfEmpty(-1).
First()
Try a Lookbehind:
Dim textboxregex As Regex = New Regex("(?<=\D)\d")
If textboxregex.IsMatch(sourceString) Then
Console.WriteLine(textboxregex.Match(sourceString).Index)
End If
This will match the first occurence of a digit after all non digit characters.
Your Regex expression is wrong (you need the '\' before the d) and you haven't defined Match
Dim sourceString As String = "abcdefg12345"
Dim textboxregex As Regex = New Regex("\d")
Dim rxMatch as Match = textboxregex.Match(sourceString)
If rxMatch.success Then
Console.WriteLine(rxMatch.Index) 'this should display the location of the first occurrence of the pattern within the sourcestring
End If

Remove all the String before :

"\:(.*)$"
Hi all i am using above expression to remove all the string before : (colon), but it is giving me all the string before this. how can i do this. Thanks a lot.
My string is:
This is text: Hi here we go
I am getting: This is text
I want : Hi here we go
Updated code
Sub Main()
Dim input As String = "This is text with : far too much "
Dim pattern As String = "\:(.*)$"
Dim replacement As String = " "
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)
Console.WriteLine("Original String: {0}", input)
' MsgBox("Original String: {0}")
Console.WriteLine("Replacement String: {0}", result)
MsgBox("Original String: {0}")
End Sub
Try this pattern. This will help you to match string after colon
/?:(.)/
or
/: (.+)/
It should be:
Dim pattern As String = "(.*)\:"
' in vb if above one doesn't work, then try this one
' Dim pattern As String = "^(.*)\:"
' also i don't think we need to use any brackets here as well.
This regex means, anything before the colon(:), Where you were using anything after the colon(:) in your example.
If you are not dead set on RegEx then you can also use
Dim result As String
result = Strings.Split(Input, ":", 2)(1)
This splits the input into an array with two elements. First element is the text before the first ":", the second element is the text after.

Is it possible to use your match from the match box in the replace box with Regex/Replace?

I have a long list like this
sb.AppendLine(product.product_id.Length.ToString())
I want to use regex search and replace to change every line to something like this
sb.AppendLine("product.product_id " + product.product_id.Length.ToString())
Is this possible to do with regex search and replace?
What do I put in the search box and what to I put in the replace box?
Is it possible to use your match from the match box in the replace box?
Yes it is possible, using capturing parentheses.
I assume that product_id is variable.
Search:
sb\.AppendLine\(product\.(.+)\.Length\.ToString\(\)\)
Replace:
sb.AppendLine("product.$1 " + product.$1.Length.ToString())
in vb .net
Dim str As String
str = "sb.AppendLine(product.product_id.Length.ToString())"
Dim RegexObj As Regex
RegexObj = New Regex("^sb.AppendLine((.*).Length.ToString())$")
Dim res As String
res = RegexObj.Replace(str, "sb.AppendLine(""$1"" + product.product_id.Length.ToString())")
in c# .net
string str = null;
str = "sb.AppendLine(product.product_id.Length.ToString())";
Regex RegexObj = default(Regex);
RegexObj = new Regex("^sb\.AppendLine\((.*)\.Length\.ToString\(\)\)$");
string res = null;
res = RegexObj.Replace(str, "sb.AppendLine(\"$1\" + product.product_id.Length.ToString())");