2011-04-08 39 views

Respuesta

4

Sí, expresiones regulares podría hacer eso para usted

que podría hacer ([0-9]+)X([0-9]+) Si sabe que los números son únicamente de un solo dígito que podría tomar [0-9]X[0-9]

2

esto puede ayudarle a

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

Mismo comentario como a continuación incorrecto para que coincida con X –

0

¿Desea el número o el índice del número? Puede obtener ambas cosas, pero lo que probablemente va a querer echar un vistazo a System.Text.RegularExpressions.Regex

El patrón real va a ser [0-9]x[0-9] si desea que sólo los números individuales (89x72 sólo coincidirá 9x7), o [0-9]+x[0-9]+ a hacer coincidir la cadena de números consecutivos más larga en ambas direcciones.

35
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; 
} 

también echar un vistazo a NextMatch que es una función muy útil

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

Para los amantes de la extensión de mí thods:

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