Regex, match string 4 or 5 digits long between "\" and "\"
I need to build a regex. 开发者_如何学JAVAthe string i want to match always starts with \ then 4 or 5 numbers then another \
For example.
- Welcome Home<\217.163.24.49\7778\False,
- Euro Server\217.163.26.20\7778\False,
- 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
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;
}
@"\\(\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]
.
Try (\\[\d]{4,5}\\)
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]+)
\\[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)
精彩评论