Quindi ho un indirizzo IP come stringa. Ho questa espressione regolare (\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3})
Come stampare i gruppi corrispondenti?Stampa regex partite in java
Grazie!
Quindi ho un indirizzo IP come stringa. Ho questa espressione regolare (\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3})
Come stampare i gruppi corrispondenti?Stampa regex partite in java
Grazie!
import java.util.regex.*;
try {
Pattern regex = Pattern.compile("(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
for (int i = 1; i <= regexMatcher.groupCount(); i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
}
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Se si utilizza Pattern e Matcher per fare la tua regex, allora si può chiedere la Matcher per ogni gruppo utilizzando il metodo di group(int group)
Quindi:
Pattern p = Pattern.compile("(\\d{1-3}).(\\d{1-3}).(\\d{1-3}).(\\d{1-3})");
Matcher m = p.matcher("127.0.0.1");
if (m.matches()) {
System.out.print(m.group(1));
// m.group(0) is the entire matched item, not the first group.
// etc...
}
Non dovrebbe essere necessario per la cattura PatternSyntaxException se il tuo regex è hardcoded (come è). Se c'è un errore nella sintassi, lo troverai la prima volta che esegui il programma. –
@mmyers: presumo la forza delle abitudini, ma hai ragione. –
Il contatore non dovrebbe iniziare su 0? –