Voici la façon dont j'irais pour éviter la dépendance aux langages communs.
public static String escapeRegexp(String regexp){
String specChars = "\\$.*+?|()[]{}^";
String result = regexp;
for (int i=0;i<specChars.length();i++){
Character curChar = specChars.charAt(i);
result = result.replaceAll(
"\\"+curChar,
"\\\\" + (i<2?"\\":"") + curChar); // \ and $ must have special treatment
}
return result;
}
public static List<String> findGroup(String content, String pattern, int group) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
List<String> result = new ArrayList<String>();
while (m.find()) {
result.add(m.group(group));
}
return result;
}
public static List<String> tokenize(String content, String firstToken, String lastToken){
String regexp = lastToken.length()>1
?escapeRegexp(firstToken) + "(.*?)"+ escapeRegexp(lastToken)
:escapeRegexp(firstToken) + "([^"+lastToken+"]*)"+ escapeRegexp(lastToken);
return findGroup(content, regexp, 1);
}
utiliser comme ceci:
String content = "hello[world]this[[is]me";
List<String> tokens = tokenize(content,"[","]");
-ce que vos jetons un caractère seulement ou peut-il être plus long? – glmxndr
peut être plus long - mon exemple était pour la simplicité mais la chaîne de début pourrait être "foo" et la chaîne de fin pourrait être "barre". – digiarnie
On dirait que Apache Commons Lang - StringUtils.substringsBetween (string, open, close) est ce dont vous avez besoin. Fonctionne comme indiqué ci-dessus, voir la réponse ci-dessous pour plus de détails. – Jon