2010-06-28 3 views

Répondre

3

Vous devez utiliser Pattern et Matcher:

Pattern pattern = Pattern.compile("<[^>]*>"); 
Matcher matcher = pattern.matcher("Peter <5554>, John <5556>,"); 
while (matcher.find()) { 
    System.out.println("index="+matcher.start()+" - "+matcher.group()); 
} 

Sortie:

index=6 - <5554> 
index=19 - <5556> 
+0

solution Nice, bien que l'OP ne demandait pas postions de ce modèle, mais pour la position des caractères '<' and '>' (mais peut-être avez-vous résolu ce qu'il regardait * vraiment *;)) –

+0

Merci à tous. J'utilise Pattern. = D True Soft, puis-je savoir plus comment faire une expression régulière? – soclose

+0

Voir http://www.regular-expressions.info/. Dans ce cas, '<' signifie que vous vous occupez de '<'; '[^>]' signifie un caractère qui n'est pas '>'; '*' est pour zéro ou plusieurs caractères, et '>' correspond '>'. Si votre contenu est formé par un ou plusieurs chiffres, vous pouvez utiliser '<\d+>'. En Java, vous devez échapper backslash: '" <\\d+> "'. –

2

Une solution consisterait à utiliser String.indexOf(). Vous pouvez faire quelque chose comme ceci:


String s = "Peter <5554>, John <5556>"; 
List<Integer> posGt = new ArrayList<Integer>(); 
int i = 0; 
while((i = s.indexOf('>', i)) != -1) { 
    posGt.add(i++); 
} 
... 
//the same for < 
2

Vous pouvez la mettre en œuvre avec répétées indexOf et substring:

String s = "Peter <5554>, John <5556>," 
int count = 0; 
ArrayList<Integer> positions = new ArrayList<Integer>(); 
int cut = 0; 
while(true) { 
    // search for < 
    int index = s.indexOf('<'); 
    if (index < 0) 
    break; 
    // search for > 
    int index2 = s.indexOf('>'); 
    if (index2 < 0) 
    break; // or throw exception 

    // update count and positions 
    count++; 
    positions.add(index+cut); 

    s = s.substring(index2+1); 
    cut += index2+1; // used to compute the initial position since we're cutting the string 
} 
0

Répété indexOf avec fromIndex ressemble à une belle solution. L'alternative aurait été itérer sur la chaîne et en utilisant charAt (sans doute la solution la plus évidente, si seulement java avait l'indexation des chaînes sain d'esprit):

String s = "Peter <5554>, John <5556>,"; 
for (int i = 0; i < s.length(); i++) { 
    if (s.charAt(i) == '<' || s.charAt(i) == '>') { 
     System.out.printf("index %d - %s\n", i, s.charAt(i)); 
    } 
} 
Questions connexes