3

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!

2 Answers 2

5

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.
Sign up to request clarification or add additional context in comments.

5 Comments

I'm probably doing something wrong, but that didn't work for me. It just returned the original string. I tried: String newMessage = message.replaceAll("(&.)", "$1&l"); System.out.print(newMessage);
@BlackBeltPanda I've compiled this code. You can take a look at it here : Java - Insert String into another String after string pattern Are you sure you're not printing message instead of newMessage?
Yes, I tried printing both to compare them and they look the same. It outputs: Original Message: &b[&3Obsidian&aAuctions&b] &5&cAttention, an auction is beginning! New Message: &b[&3Obsidian&aAuctions&b] &5&cAttention, an auction is beginning! It's like it doesn't want to match the regex.
@BlackBeltPanda can you please edit your question and provide a Minimal, Complete, and Verifiable example.
Actually just figured it out. Another method was changing the "&" to a "§" so I modified the regex to look for "(§.)" and replace with "$1§l". Thank you!
0

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;
    }
}

Comments

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.