Can i use regex to find the index of X?

后端 未结 7 1289
遇见更好的自我
遇见更好的自我 2020-12-15 07:45

I have a big string, and want to find the first occurrence of X, X is \"numberXnumber\"... 3X3, or 4X9...

How could i do this in C#?

相关标签:
7条回答
  • 2020-12-15 08:10

    Yes, regex could do that for you

    you could do ([0-9]+)X([0-9]+) If you know that the numbers are only single digit you could take [0-9]X[0-9]

    0 讨论(0)
  • 2020-12-15 08:16

    For those who love extension methods:

    public static int RegexIndexOf(this string str, string pattern)
    {
        var m = Regex.Match(str, pattern);
        return m.Success ? m.Index : -1;
    }
    
    0 讨论(0)
  • 2020-12-15 08:22
    var index = new Regex("yourPattern").Match("X").Index;
    
    0 讨论(0)
  • 2020-12-15 08:25

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

    You can use this pattern:

    \d([xX])\d

    If I test

    blaat3X3test

    I get:

    Match offset: 5 Match length: 3 Matched text: 3X3 Group 1 offset: 6 Group 1 length: 1 Group 1 text: X

    0 讨论(0)
  • 2020-12-15 08:29

    Do you want the number, or the index of the number? You can get both of these, but you're probably going to want to take a look at System.Text.RegularExpressions.Regex

    The actual pattern is going to be [0-9]x[0-9] if you want only single numbers (89x72 will only match 9x7), or [0-9]+x[0-9]+ to match the longest consecutive string of numbers in both directions.

    0 讨论(0)
  • 2020-12-15 08:31

    this may help you

       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;
    
    0 讨论(0)
提交回复
热议问题