2009-10-09 6 views
0

J'ai une chaîne qui ressemble à ceci: mynum(1234) and mynum(123) and mynum (12345) and lastly mynum(#123)en utilisant java regex comment puis-je remplacer tous quand modèle contient des parenthèses gauche

Je veux insérer un # devant les chiffres entre parenthèses, donc j'ai: mynum(#1234) and mynum(#123) and mynum (#12345) and lastly mynum(#123)

Comment est-ce que je peux faire ceci? Utiliser modèle regex matcher et un replaceAll étranglements sur le ( devant le nombre et je reçois un

java.util.regex.PatternSyntaxException: groupe Unclosed près ...

exception.

Répondre

4

Essayez:

String text = "mynum(1234) and mynum(123) and foo(123) mynum (12345) and lastly mynum(#123)"; 
System.out.println(text.replaceAll("mynum\\s*\\((?!\\s*#)", "$0#")); 

Une petite explication:

Remplacer chaque modèle:

mynum // match 'mynum' 
\s*  // match zero or more white space characters 
\(  // match a '(' 
(?!  // start negative look ahead 
    \s* // match zero or more white space characters 
    #  // match a '#' 
)  // stop negative look ahead 

avec la sous-chaîne:

$0# 

Où 0 $ contient le texte c'est matc hed par toute la regex.

+0

Génial !!! Ça a marché. Aussi, merci pour l'explication. C'était très utile. Maintenant, j'ai juste besoin de faire des recherches pour comprendre ce qui est "regard négatif" –

+0

@KT: jetez un oeil à ce tutoriel: http://www.regular-expressions.info/lookaround.html –

Questions connexes