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