示例:我想在名为 target 的字符串中查找 1234:
string target = "55555>>><<[1234]<>>>788";
如何在不知道 []、之前 [ 或之后 ] 之间有多少位的情况下找到 [,] 之间的数字?我的项目需要一个小代码。
谢谢。
示例:我想在名为 target 的字符串中查找 1234:
string target = "55555>>><<[1234]<>>>788";
如何在不知道 []、之前 [ 或之后 ] 之间有多少位的情况下找到 [,] 之间的数字?我的项目需要一个小代码。
谢谢。
using System.Text.RegularExpressions;
...
// Declare target
string target = "55555>>><<[1234]<>>>788";
// Declare the regular expression
Regex regex = new Regex(
@"(?<=\[)[0-9]+(?=\])",
RegexOptions.None
);
// Use regex to get value
string number = regex.Match(target).Value;
// Convert to number (optional)
int value = 0;
int.TryParse(number, out value);
// Note: value will be 0 if no matches are found.
What this regex does:
The first bit (?<=\[)
is a "look behind". It ensures that a bracket proceeds the numbers. You have to escape it with a backslash because brackets are special characters in a regex.
The middle bit [0-9]+
looks for one or more of any digit. If you wanted zero or more, you could use a star instead of a plus: [0-9]*
The last bit (?=\])
is a "look ahead" similar to the "look behind". Again the bracket is escaped.
The output will be only the numbers without the brackets but only when the numbers are surrounded by brackets.
This sounds like a job for regular expressions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string str = "55555>>><<[1234]<>>>788";
Regex r = new Regex(@"\[(\d*)\]");
Match match = r.Match(str);
Console.WriteLine(match.Groups[1].Value);
}
}
}
the above code has the following output
1234
Press any key to continue . . .
Here is a regex which does the trick:
Console.WriteLine (Regex.Match("55555>>><<[1234]<>>>788", @"(?:\[)(?<Data>[^\]]+)(?:\])").Groups["Data"].Value);
// 1234 is outputed
以下应该足够了:
var match = Regex.Match("55555>>><<[1234]<>>>788", ".*\[(.+)\].*");
var value = match.Groups[1].Value; //= "1234"
如果 value 应该始终是一个数字,您可以在其他答案中替换为(.+)
。(\d+)
.+
表示任何字符
\d
表示任何数字 0 到 9。