0

I need to replace string with a variable inside {} using a regex

For example:

"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"

Inside the Strings variables inside {} can be more than 1

I need this code to allow users to modify messages. variable inside {} after @ like in the example 'US-server' are put in by users so there aren't list to check for variable. Variables could be as strange as possible ex: '{online@test-UK}' '{online@asdtest}'

public static String getReplaced(String d) {
    String result = d.split("\\{online@")[0];

    for (int i = 1; i < d.split("\\{online@").length; i++) {
        String dd = d.split("\\{online@")[i];

        Pattern p = Pattern.compile("(.*?)}(.*)");
        Matcher m = p.matcher(dd);

        if (m.lookingAt()) {
            int count = 12;

            result += count + m.group(2);
        } else {
            result += dd;
        }
    }

    return result;
}
7
  • 1
    what did you try? Commented Feb 19, 2020 at 16:10
  • @jhamon I tried a lot of things but I have no familiarity with those things... The last I tried was "{online@(.*?)}(.*)" Commented Feb 19, 2020 at 16:12
  • 3
    Please edit your question to include the code you've tried, even if you think it's wrong Commented Feb 19, 2020 at 16:12
  • You probably shouldn't use regex anyway baeldung.com/… Commented Feb 19, 2020 at 16:14
  • @cricket_007 I added the code. I tried many times to do the thing so sorry for my bad code. Commented Feb 19, 2020 at 16:16

3 Answers 3

1

With \\{online@(.+)\\}as the regex, use a matcher to get the first capturing group. That will give you the part after the @.

Regex means:

  • \\{: litteral character '{'
  • online@: the string online@
  • .+: at least one character (anyone)
  • (.+): capturing group
  • \\}: litteral character '}'

Then simply use String#replaceAll(String regex, String replacement) (doc here).

Example:

int myIntValue = 12;
String myString = "there are {online@US-server} players";
Pattern p = Pattern.compile("\\{online@(.+)\\}") ;
Matcher m = p.matcher(myString) ;

if (m.find()) { // true if the pattern is found anywhere in your string.
  System.out.println("Variable part is : " + m.group(1)); // group 1 is the capturing group
  System.out.println(myString.replaceAll("\\{online@.+\\}", String.valueOf(myIntValue)));
}

If you need to find more than one placeholder in a single string:

String myString = "there are {online@US-server} players ,and {online@whatever}";
Pattern p = Pattern.compile("\\{online@(.+)\\}") ;
Matcher m = p.matcher(myString) ;

while (m.find()) { // true if the pattern is found anywhere in your string.
  System.out.println("Variable part is : " + m.group(1)); // group 1 is the capturing group
  System.out.println(myString.replace("{online@"+m.group(1)+"}", String.valueOf(myIntValue)));
}
Sign up to request clarification or add additional context in comments.

5 Comments

It's the first sentence of my answer. You just need to convert the int to a String.
Okay your code work to change all {} to a int but now I must know what int. How many players are online in the server? i need to change all {} with players in the server name after @
I need to know what is between {server@ and } and with this do the replace
Your code worked. thanks a lot for your time. Your regex didn't work so I changed it with (.*?)
Strange. I tryed it and it worked fine. Could it be that you allow empty value after the @?
1

You don't need regex for this, and probably shouldn't use it, because using user input as a regex has some potential security risks.

public String replaceTag(String tag, String replacement, String template) {
   private final String decoratedTag = "{online@" + tag + "}";

   return template.replace(decoratedTag, replacement);
}

You can call this repeatedly:

private String template = getTemplateFromUser();
private String output = template.replace('US-server', usServerCount);
output = output.replace('asdtest', testValue);
return output;

... or you can be more sophisticated and loop through a set of tag/value pairs, for example from a Map<String, String>

Note that String.replace() just replaces character sequences dumbly, it's not a regular expression replace, which for this problem is a good thing.

2 Comments

I don't have a list of path with variables. Every user put what they want like 'US-server' or 'Test-server' and through another method, you get player counter in the server. So after @ there is the server's name
@kratess then I think you need to go back to your question, and carefully rewrite it to explain the requirement.
0
([^\s]+)online@[A-Za-z\-]([^\s]+)

seems to work.

1 Comment

This may answer the question. However, code only answers are not as useful as answers that document the code or have an detailed explanation on why this code is the solution to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.