My coworker needs me to write him a regular expression for his vb.net app.
I do not know vb and he does not know regex.
The regex he needs is:
/.*web id: ?(\d+).*/i
Basically he needs to search a string for something like “web id: 345” or “web id:2534” and retrieve the ID.
He took what I gave him above and was able to put this together:
Dim strPattern As String = ".*web id: ?(\d+).*"
Dim strReplacement$ = "$1"
GetWebId$ = Regex.Replace(LCase$(strNote$), strPattern$, strReplacement$)
However I am not sure how you pass the case-insensitive flag? (his current fix for that is making the whole string lowercase first)
Also one thing I can’t seem to figure out is when he runs this on a string with multiple lines, any text that is not on the same line as “web id: \d” is also being returned which i find strange.
Use the
RegexOptions.IgnoreCaseflag:If you are going to ignore case there should be no need to use
LCase. I also find it odd that you have all those$symbols in your variable names – they shouldn’t be valid in either C# or VB.NET.EDIT #2: I realize you may have wanted to replace the entire line that matched with the
$1replacement pattern to match the ID. If you have a need to use multiple options you canOrthem together as follows:EDIT #1: you are using the wrong method to extract the ID. You have a group
(\d+)to capture the ID, but you are usingRegex.Replaceon your match, which is why you get everything else in the text. To match the ID use the following:You will notice we refer to
Groups(1)which holds the value captured by the(\d+)group. Patterns with more groups may lead to confusion, especially with nested groups. In those cases you can use named groups. Here is the same code updated to use named groups: