Si prega di dare un'occhiata al seguente codice:
public static void main(String[] args) {
String s = "a < b > c > d";
String regex = "(\w\s*[<>]\s*\w)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
int i = 0;
while (m.find()) System.out.println(m.group(i++));
}
L'output del programma di cui sopra è: a < b, c > d
Ma in realtà mi aspetto a < b, b > c, c > d
.
Qualcosa che non va con il mio regexp qui?
risposte:
2 per risposta № 1Prova questo.
String s = "a < b > c > d";
String regex = "(?=(\w{1}\s{1}[<>]{1}\s{1}\w{1})).";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1));
}
Aggiornato (basato sulla soluzione verde):
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d";
String regex = "(?=[\s,;]+|(?<![\w\/\-\.])([\w\/\-\.]+\s*[<>]\s*[\w\/\-\.]+))";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while (m.find()) {
String d = m.group(1);
if(d != null) {
System.out.println(d);
}
}
3 per risposta № 2
Hai ragione nel pensare che b> c corrisponde alla regex perché lo fa.
Ma quando chiami Matcher :: find (), restituisce la sottostringa successiva dell'input che corrisponde alla regex e è disgiunto dalle corrispondenze find () precedenti. Poiché "b> c" inizia con la "b" che faceva parte della corrispondenza "a> b" restituita dall'invocazione precedente, non viene restituita da find ().
1 per risposta № 3
Basato sulla soluzione di John e aggiungendo alcuni abbinamenti di confini, questo funziona alla fine.
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d";
String regex = "(?=[\s,;]+([\w\/\-\.]+\s*[<>]\s*[\w\/\-\.]+)[\s,;$]*).";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1));
}