tags:

views:

95

answers:

5

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

+1  A: 

Try (\\[\d]{4,5}\\)

Daniel A. White
Why the square brackets around \d? That just makes it a set with one member.
JasonFruit
ok i did this, and it actually keeps the "\"'s
brux
i need to imit the when i use regex.match.success to get the matched string is there a way to omit the "\"'s?
brux
+3  A: 
@"\\(\d{4,5})\\"

\\ to match a backslash, \d to match digits, {4,5} for "4 to 5". The parentheses around \d{4,5} make it so that you can access the number part with .Groups[1].

sepp2k
hi sepp2k, i tried this and its keeping the "\" either side of the 4/5 digit number. i need just the number
brux
@brux: As I said in my edit, the number will be in the first capturing group if you put the parentheses around `\d{4,5}`.
sepp2k
var match1 = Regex.Match(temp, @"\\(\d{4,5})\\");if (match1.Success) ipaddr.Text = match1.Captures[0].ToString(); the string in the text box is \7778\ not 7778 :s
brux
@brux: Right, you need to do `Groups[1]`, not `Captures[0]` to access the content of the first group.
sepp2k
A: 

I've developed a simple tool to verify regexes against example strings; this is a valid string for your samples in C#, it however is not 'strict'!

(?<name>.+?)\\(?<ip>[0-9.]+)\\(?<port>[0-9]{4,5})\\(?<boolean>[False|True]+)

Kolky
A: 
\\[0-9]{4,5}\\

\ It should start with \ (another \ is to escape)
[0-9] It could be any of the number mentioned in set (0,1,2,3...9)
{4,5} previous set can appear 4 to 5 times
\ It should end with \ (another \ is to escape)

Narendra Kamma
+2  A: 
var match=Regex.Match(@"\1234\",@"\\(?<num>\d{4,5})\\"); \\"to fix SO syntax highlighter


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;
}
spender