【问题标题】:Can i use regex to find the index of X?我可以使用正则表达式来查找 X 的索引吗?
【发布时间】:2011-04-08 07:16:18
【问题描述】:

我有一个大字符串,想找出第一次出现的X,X是“numberXnumber”...3X3,还是4X9...

我如何在 C# 中做到这一点?

【问题讨论】:

    标签: c# regex


    【解决方案1】:
    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,这是一个方便的功能

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

    【讨论】:

      【解决方案2】:

      是的,正则表达式可以为您做到这一点

      你可以([0-9]+)X([0-9]+) 如果你知道这些数字只有一位数,你可以用[0-9]X[0-9]

      【讨论】:

        【解决方案3】:

        对于喜欢扩展方法的人:

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

        【讨论】:

          【解决方案4】:

          这可能对你有帮助

             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;
          

          【讨论】:

            【解决方案5】:
            var index = new Regex("yourPattern").Match("X").Index;
            

            【讨论】:

              【解决方案6】:

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

              你可以使用这个模式:

              \d([xX])\d

              如果我测试

              blaat3X3test

              我明白了:

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

              【讨论】:

                【解决方案7】:

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

                如果您只需要单个数字(89x72 将只匹配 9x7),实际模式将是 [0-9]x[0-9],或者 [0-9]+x[0-9]+ 以匹配两个方向上最长的连续数字字符串。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2010-09-29
                  • 2013-01-30
                  • 2015-03-21
                  • 2013-05-23
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-03-31
                  相关资源
                  最近更新 更多