[英]Regex, match string 4 or 5 digits long between “\” and “\”
I need to build a regex. 我需要建立一个正则表达式。 the string i want to match always starts with \\ then 4 or 5 numbers then another \\ 我要匹配的字符串始终以\\然后4或5个数字开头,然后是另一个\\
For example. 例如。
in first example i need "7778". 在第一个例子中,我需要“7778”。 In second example i need "7778". 在第二个例子中,我需要“7778”。 In third example i need "8278". 在第三个例子中,我需要“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. 这4位数字实际上是一个端口号,它是每一行上唯一出现这一系列字符(例如\\ 7778 \\)的时间。 sometimes the port number is 4 digits long, sometimes its 5. 有时端口号是4位数,有时是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. 我已经知道如何保留字符串供以后使用Regex.Match.Success,它只是我在这里寻找的实际正则表达式模式。
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: 或者(如果你不喜欢使用组)你可以使用lookbehind和lookahead断言来确保你的4-5位数匹配被斜线包围:
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". \\\\
匹配反斜杠, \\d
匹配数字, {4,5}
代表“4到5”。 The parentheses around \\d{4,5}
make it so that you can access the number part with .Groups[1]
. 围绕\\d{4,5}
的括号使得您可以使用.Groups[1]
访问数字部分。
试试(\\\\[\\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'! 这是C#中样本的有效字符串,但它不是“严格”的!
(?<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) [0-9]它可以是集合中提到的任何数字(0,1,2,3 ... 9)
{4,5} previous set can appear 4 to 5 times {4,5}之前的设定可以出现4至5次
\\ It should end with \\ (another \\ is to escape) 它应以\\结尾(另一个\\是逃避)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.