Ottieni l'indice di un pattern in una stringa usando regex


Risposte:


166

Usa Matcher :

public static void printMatches(String text, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    // Check all occurrences
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end());
        System.out.println(" Found: " + matcher.group());
    }
}

5

risposta in edizione speciale di Jean Logeart

public static int[] regExIndex(String pattern, String text, Integer fromIndex){
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {
        return new int[]{matcher.start(), matcher.end()};
    }
    return new int[]{-1, -1};
}

-2
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "This order was places for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Risultato

Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0

2
Si prega di commentare durante il downvoting! @ Shadow Presumo che questo sia stato downvoted in quanto non fornisce, come richiesta OP, l'indice della partita ...
El Ronnoco

4
Va bene ... ho downvoted perché questa risposta non affronta la domanda.

3
Anche la tua regex è difettosa. Il primo (.*)consuma originariamente l'intera stringa, quindi arretra quanto basta per far (\d+)corrispondere una cifra, lasciando poi il secondo (.*)a consumare ciò che è rimasto. Non è un risultato particolarmente utile, direi. Oh, e hai lasciato group(3)fuori i tuoi risultati.
Alan Moore,

2
Non dà l'indice
piratemurray il
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.