2011-12-16 3 views
1

J'ai une chaîne commeRechercher une sous-chaîne entre caractères spéciaux dans une chaîne

(&(objectclass=${abc})(uid=${xyz})) 

Comment puis-je effectuer des recherches $ {abc} et $ {} xyz et le remplacer par une autre cordes. Il peut y avoir n'importe quel nombre d'occurrences de telles sous-chaînes, c'est-à-dire $ {abc} dans la chaîne principale. Je pensais à string.indexOf( mais cela pourrait être désordonné. Une meilleure approche?

$ {abc} sera remplacé par une autre chaîne abc. Je vais les obtenir à partir d'autres paramètres.

+0

Et vous voulez remplacer par quoi? Avez-vous une sorte de carte pour les remplacements? – fge

+0

remplacer par des chaînes simples. $ {abc} sera remplacé par une autre chaîne abc –

+0

Oui, mais d'où tenez-vous ces chaînes? – fge

Répondre

1

J'utiliserais String.indexOf(String sep, int start) dans une boucle à plusieurs reprises pour copier du texte et des valeurs dans un StringBuilder.


Quelque chose comme

public static void main(String... args) throws IOException { 
    Map<String, String> map = new LinkedHashMap<>(); 
    map.put("abc", "ABC"); 
    map.put("xyz", "XYZ"); 
    printSubstitue("nothing to change", map); 
    printSubstitue("(&(objectclass=${abc})(uid=${xyz})(cn=${cn})(special='${'))", map); 
} 

private static void printSubstitue(String text, Map<String, String> map) { 
    String text2 = subtitue(text, map); 
    System.out.println("substitue("+text+", "+map+") = "+text2); 
} 

public static String subtitue(String template, Map<String, String> map) { 
    StringBuilder sb = new StringBuilder(); 
    int prev = 0; 
    for (int start, end; (start = template.indexOf("${", prev)) > 0; prev = end + 1) { 
     sb.append(template.substring(prev, start)); 
     end = template.indexOf('}', start + 2); 
     if (end < 0) { 
      prev = start; 
      break; 
     } 
     String key = template.substring(start + 2, end); 
     String value = map.get(key); 
     if (value == null) { 
      sb.append(template.substring(start, end + 1)); 
     } else { 
      sb.append(value); 
     } 

    } 
    sb.append(template.substring(prev)); 
    return sb.toString(); 
} 

impressions

substitue(nothing to change, {abc=ABC, xyz=XYZ}) = nothing to change 
substitue((&(objectclass=${abc})(uid=${xyz})(cn=${cn})(special='${')), {abc=ABC, xyz=XYZ}) 
    = (&(objectclass=ABC)(uid=XYZ)(cn=${cn})(special='${')) 

Il devient malpropre si vous voulez soutenir ${ } imbriquées les valeurs. ;)

abc123=ghi123 
abc${xyz}=def${xyz} 

(&(objectclass=${abc${xyz}})(uid=${xyz})) 

Je vous suggère de garder les choses simples si vous le pouvez. ;)

2

Vous devez extraire les caractères spéciaux ($, {, }). Essayez ceci:

str.replaceAll("\\$\\{abc\\}","abc"); 

Cela peut être bizarre, mais peut vous aider:

str = str.substring(str.indexOf("${")+2, str.indexOf("}")) 

Cela fonctionne pour tous (nombre illimité) entre chaînes ${ et }.

+0

Comment puis-je connaître son abc. Il peut être "abcdef" –

+0

@imrantariq voir la modification en réponse. –

0

La regex dont vous avez besoin est \$\{[^}]+\}. Remplacez avec tout ce qui est nécessaire.

edit: OK, j'ai mal compris la question. Regex fixe.

0

A regex comme cela fonctionne:

String regex = "(\\$\\{YOUR_TOKEN_HERE\\})"; 

Voici un exemple d'utilisation:

public static void main(String[] args) throws Exception { 
    String[] lines = { 
     "(&(objectclass=${abc})(uid=${xyz}))", 
     "(&(objectclass=${abc})(uid=${xyz})(xyz=${xyz})(abc=${abc}))" 
    }; 

    String token = "abc"; // or whatever 

    String regex = String.format("(\\$\\{%s\\})", token); 
    Pattern p = Pattern.compile(regex); 
    for (String s: lines) { 
     Matcher m = p.matcher(s); 
     if (m.find()) { 
      System.err.println(m.replaceAll("###")); 
     } 
    } 
} 

sortie pour jeton = "abc" est la suivante:

(&(objectclass=###)(uid=${xyz})) 
(&(objectclass=###)(uid=${xyz})(xyz=${xyz})(abc=###)) 
+0

Merci. Comment puis-je savoir que c'est abc et xyz? Il peut être abcd ou asdfgsdf –

+0

Oh je vois. J'ai mis à jour la réponse. – sudocode

Questions connexes