Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, match string 4 or 5 digits long between "\" and "\"

Tags:

c#

regex

I need to build a regex. the string i want to match always starts with \ then 4 or 5 numbers then another \

For example.

  1. Welcome Home<\217.163.24.49\7778\False,
  2. Euro Server\217.163.26.20\7778\False,
  3. Instagib!)\85.236.100.115\8278\False,

in first example i need "7778". In second example i need "7778". In third example i need "8278".

these 4 digit numbers is actually a port number, and its the only time on each line that this series of characters (eg, \7778\ ) would appear. sometimes the port number is 4 digits long, sometimes its 5.

I already know how to keep the string for later use using Regex.Match.Success, its just the actual regex pattern I am looking for here.

thanks

like image 204
brux Avatar asked Dec 16 '22 21:12

brux


1 Answers

var match=Regex.Match(@"\1234\",@"\\(?<num>\d{4,5})\\"); 


if(match.Success)
{
    var numString=match.Groups["num"].Value;
}

or (if you don't like using groups) you can use lookbehind and lookahead assertions to ensure your 4-5 digit match is surrounded by slashes:

var match=Regex.Match(@"\1234\",@"(?<=\\)\d{4,5}(?=\\)");
if(match.Success)
{
    var numString=match.Value;
}
like image 168
spender Avatar answered Dec 29 '22 17:12

spender