web-dev-qa-db-fra.com

Extraire la chaîne entre deux chaînes dans java

J'essaie d'obtenir une chaîne entre <% = et%>, voici mon implémentation:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>");
String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));

il retourne

[ZZZZL ,  AFFF ]

Mais mon attente est la suivante:

[ dsn , AFG ]

Où est-ce que je me trompe et comment le corriger?

34
Tien Nguyen

Votre modèle est bien. Mais vous ne devriez pas être split() en train de l'éliminer, vous devriez find() le. Le code suivant donne la sortie que vous recherchez:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}
63
jlordo

J'ai répondu à cette question ici: https://stackoverflow.com/a/38238785/1773972

Essentiellement utiliser

StringUtils.substringBetween(str, "<%=", "%>");

Cela nécessite l’utilisation de la bibliothèque "Apache commons lang": https://mvnrepository.com/artifact/org.Apache.commons/commons-lang3/3.4

Cette bibliothèque a beaucoup de méthodes utiles pour travailler avec string, vous aurez vraiment avantage à explorer cette bibliothèque dans d'autres zones de votre code Java code !!!

24
Pini Cheyni

Votre expression rationnelle semble correcte, mais vous êtes splitting avec elle au lieu de matching avec elle. Vous voulez quelque chose comme ça:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}
3
Henry Keiter

L'approche Jlordo couvre une situation spécifique. Si vous essayez de construire une méthode abstraite à partir de celle-ci, vous pouvez faire face à une difficulté pour vérifier si 'textFrom' est avant 'textTo'. Sinon, method peut renvoyer une correspondance pour une autre occurrence de 'textFrom' dans le texte.

Voici une méthode abstraite prête à l'emploi qui couvre cet inconvénient:

  /**
   * Get text between two strings. Passed limiting strings are not 
   * included into result.
   *
   * @param text     Text to search in.
   * @param textFrom Text to start cutting from (exclusive).
   * @param textTo   Text to stop cuutting at (exclusive).
   */
  public static String getBetweenStrings(
    String text,
    String textFrom,
    String textTo) {

    String result = "";

    // Cut the beginning of the text to not occasionally meet a      
    // 'textTo' value in it:
    result =
      text.substring(
        text.indexOf(textFrom) + textFrom.length(),
        text.length());

    // Cut the excessive ending of the text:
    result =
      result.substring(
        0,
        result.indexOf(textTo));

    return result;
  }
2
Zon