How to replace a particular string with value in java

EDIT :

Goal : http://localhost:8080/api/upload/form/test/test

Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.

i have following string

http://localhost:8080/api/upload/form/{uploadType}/{uploadName}

there can be any no of strings like {uploadType}/{uploadName}.

how to replace them with some values in java?

Answers


[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:

Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
    String subst = m.group( 1);
    index = m.start();
    //
    String replacement = "replacement";       // .. lookup Subst -> Replacement here
    sb.replace( index, m.end(), replacement);
    index = index + replacement.length();
}

Look, I'm really expecting a +1 now.


[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().

For multiple dynamic replacements:

public String substituteStr (String template, Map<String,String> substs) {
    String result = template;
    for (Map.Entry<String,String> subst : substs.entrySet()) {
        String pattern = "{"+subst.getKey()+"}";
        result = result.replace( pattern, subst.getValue());
    }
    return result;
}

That's the quick & easy approach, to start with.


Need Your Help

How to make Jtable forbid duplicates

java jtable

I have a Jtable allow editing and inserting.

Recognising text and displaying it

processing

I have programmed a paint application in the processing programming language. I want the letters and/or words I or a user places on the paint application to be recognised and to be printed out in a

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.