我可以使用正则表达式来查找X的索引吗?

我有一个大字符串,想要找到X的第一个出现,X是“numberXnumber”… 3X3,或4X9 ……

我怎么能在C#中做到这一点?

是的,正则表达式可以帮到你

你可以做([0-9]+)X([0-9]+)如果你知道这些数字只是一位数你可以拿[0-9]X[0-9]

 var s = "long string.....24X10 .....1X3"; var match = Regex.Match(s, @"\d+X\d+"); if (match.Success) { Console.WriteLine(match.Index); // 16 Console.WriteLine(match.Value); // 24X10; } 

另请NextMatch ,这是一个方便的function

 match = match.NextMatch(); match.Value; // 1X3; 

这可能对你有帮助

  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; 
 var index = new Regex("yourPattern").Match("X").Index; 

对于喜欢扩展方法的人:

 public static int RegexIndexOf(this string str, string pattern) { var m = Regex.Match(str, pattern); return m.Success ? m.Index : -1; } 

http://www.regular-expressions.info/download/csharpregexdemo.zip

你可以使用这种模式:

\ d([XX])\ d

如果我测试

blaat3X3test

我明白了:

匹配偏移量:5匹配长度:3匹配文本:3X3组1偏移量:6组1长度:1组1文本:X

您想要数字还是数字的索引? 你可以得到这两个,但你可能想要看看System.Text.RegularExpressions.Regex

如果你只需要一个数字(89×72只能匹配9×7),或者[0-9]+x[0-9]+匹配最长的数字,实际模式将是[0-9]x[0-9]两个方向上的连续数字串。