BlackBeltPanda
BlackBeltPanda

Reputation: 33

Java - Insert String into another String after string pattern?

I'm trying to figure out how to insert a specific string into another (or create a new one) after a certain string pattern inside the original String.

For example, given this string,

"&2This is the &6String&f."

How would I insert "&l" after all "&x" strings, such that it returns,

"&2&lThis is the &6&lString&f&l."

I tried the following using positive look-behind Regex, but it returned an empty String and I'm not sure why. The "message" variable is passed into the method.

    String[] segments = message.split("(?<=&.)");

    String newMessage = "";

    for (String s : segments){
        s.concat("&l");
        newMessage.concat(s);
    }

    System.out.print(newMessage);

Thank you!

Upvotes: 3

Views: 7572

Answers (2)

Kevin Ng
Kevin Ng

Reputation: 2174

My answer would be similar to the one above. It just this way would be reusable and customizable in many circumstances.

public class libZ
{
    public static void main(String[] args)
    {
        String a = "&2This is the &6String&f.";
        String b = patternAdd(a, "(&.)", "&l");
        System.out.println(b);
    }

    public static String patternAdd(String input, String pattern, String addafter)
    {
        String output = input.replaceAll(pattern, "$1".concat(addafter));
        return output;
    }
}

Upvotes: 0

Raman Sahasi
Raman Sahasi

Reputation: 31841

You can use:

message.replaceAll("(&.)", "$1&l")
  • (&.) finds pattern where an ampersand (&) is followed by anything. (&x as you've written).
  • $1&l says replace the captured group by the captured group itself followed by &l.

code

String message = "&2This is the &6String&f.";
String newMessage = message.replaceAll("(&.)", "$1&l"); 
System.out.println(newMessage);

result

&2&lThis is the &6&lString&f&l.

Upvotes: 5

Related Questions