C# 我可以使用正则表达式来查找X的索引吗?
我有一个大字符串,想找到X的第一个匹配项,X是“numberXnumber”。。。3X3或4X9 我怎样才能在C#中做到这一点?这可能会对您有所帮助C# 我可以使用正则表达式来查找X的索引吗?,c#,regex,C#,Regex,我有一个大字符串,想找到X的第一个匹配项,X是“numberXnumber”。。。3X3或4X9 我怎样才能在C#中做到这一点?这可能会对您有所帮助 string myText = "33x99 lorem ipsum 004x44"; //the first matched group index int firstIndex = Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Index; //first matche
string myText = "33x99 lorem ipsum 004x44";
//the first matched group index
int firstIndex = Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Index;
//first matched "x" (group = 2) index
int firstXIndex = Regex.Match(myText,"([0-9]+)(x)([0-9]+)").Groups[2].Index;
是的,regex可以帮你
如果您知道数字是唯一的一位数,您可以选择
([0-9]+)X([0-9]+)
,您想要数字还是数字的索引?你可以得到这两个,但你可能会想看看
如果只需要单个数字(89x72只匹配9x7),实际模式将是[0-9]x[0-9]
,或者[0-9]+x[0-9]+
匹配两个方向上最长的连续数字串。
您可以使用以下模式:
\d([xX])\d
如果我测试
Blaat3x3测试
我得到:
匹配偏移量:5匹配长度:3
匹配文本:3X3第1组偏移量:6
第1组长度:1第1组文字:X
另请看一看NextMatch
,这是一个方便的功能
match = match.NextMatch();
match.Value; // 1X3;
对于那些喜欢扩展方法的人:
public static int RegexIndexOf(this string str, string pattern)
{
var m = Regex.Match(str, pattern);
return m.Success ? m.Index : -1;
}
match = match.NextMatch();
match.Value; // 1X3;
public static int RegexIndexOf(this string str, string pattern)
{
var m = Regex.Match(str, pattern);
return m.Success ? m.Index : -1;
}