例子:我想找到1234在一个字符串指定的目标:查找字符串
string target = "55555>>><<[1234]<>>>788";
我如何才能找到与[,]数不知道如何[]之前[或之后]之间多少数字?我需要我的项目的一个小代码。
谢谢。
例子:我想找到1234在一个字符串指定的目标:查找字符串
string target = "55555>>><<[1234]<>>>788";
我如何才能找到与[,]数不知道如何[]之前[或之后]之间多少数字?我需要我的项目的一个小代码。
谢谢。
这听起来像是正则表达式
工作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);
}
}
}
上面的代码中有以下输出
1234
Press any key to continue . . .
感谢,这正是我需要的 – Krestek
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.
什么这个表达式的作用:
第一位(?<=\[)
是 “向后看”。它可以确保一个支架继续进行编号。因为括号是正则表达式中的特殊字符,所以必须使用反斜线进行转义。
中间位[0-9]+
寻找一个或多个任何数字的。如果你想零个或更多,你可以使用一颗星而不是一个加号:[0-9]*
最后一位(?=\])
是一种类似于“后视”的“向前看”。支架再次逃脱。
的输出将是唯一的数字没有括号但只有当数由括号包围。
这里是一个正则表达式该做的伎俩:
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"
如果值应该始终是一个数字,您可以用(\d+)
替代(.+)
,就像在其他答案中一样。
.+
指任何字符
\d
指任何数字0到9
如果你使用'*'或'\ d *'然后这允许[]之间的0字符。使用'+'确保至少有一个字符/数字。 –
听起来像是正则表达式工作 –
你能拥有比字符串中设置的[]吗? – RobH