Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regular expression find and replace

Tags:

java

regex

I am trying to find environment variables in input and replace them with values.

The pattern of env variable is ${\\.}

Pattern myPattern = Pattern.compile( "(${\\.})" );
String line ="${env1}sojods${env2}${env3}";

How can I replace env1 with 1 and env2 with 2 and env3 with 3, so that after this I will have a new string 1sojods23?

like image 238
user1205079 Avatar asked Mar 07 '12 16:03

user1205079


People also ask

How do I find and replace in a regular expression in Java?

They can be used to search, edit, or manipulate text and data. The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.

How do you replace a character in a string in Java regex?

To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.


3 Answers

Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace.

Specifically you need to define your replacements in a Map, use a StringBuilder (before Java 9, less performant StringBuffer should have been used) and the appendReplacements() and appendTail() methods from Matcher. The final result will be stored in your StringBuilder (or StringBuffer).

Map<String, String> replacements = new HashMap<String, String>() {{
    put("${env1}", "1");
    put("${env2}", "2");
    put("${env3}", "3");
}};

String line ="${env1}sojods${env2}${env3}";
String rx = "(\\$\\{[^}]+\\})";

StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9
Pattern p = Pattern.compile(rx);
Matcher m = p.matcher(line);

while (m.find())
{
    // Avoids throwing a NullPointerException in the case that you
    // Don't have a replacement defined in the map for the match
    String repString = replacements.get(m.group(1));
    if (repString != null)    
        m.appendReplacement(sb, repString);
}
m.appendTail(sb);

System.out.println(sb.toString());

Output:

1sojods23
like image 100
Brian Roach Avatar answered Oct 05 '22 23:10

Brian Roach


I know this is old, I was myself looking for a, appendReplacement/appendTail example when I found it; However, the OP's question doesn't need those complicated multi-line solutions I saw here.

In this exact case, when the string to replace holds itself the value we want to replace with, then this could be done easily with replaceAll:

String line ="${env1}sojods${env2}${env3}";

System.out.println( line.replaceAll("\\$\\{env([0-9]+)\\}", "$1") );

// Output => 1sojods23

DEMO

When the replacement is random based on some conditions or logic on each match, then you can use appendReplacement/appendTail for example

like image 25
Enissay Avatar answered Oct 06 '22 01:10

Enissay


Hopefully you would find this code useful:

    Pattern phone = Pattern.compile("\\$\\{env([0-9]+)\\}");
    String line ="${env1}sojods${env2}${env3}";
    Matcher action = phone.matcher(line);
    StringBuffer sb = new StringBuffer(line.length());
    while (action.find()) {
      String text = action.group(1);
      action.appendReplacement(sb, Matcher.quoteReplacement(text));
    }
    action.appendTail(sb);
    System.out.println(sb.toString());

The output is the expected: 1sojods23.

like image 33
Boris Strandjev Avatar answered Oct 05 '22 23:10

Boris Strandjev