Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-在字符串模式之后将字符串插入另一个字符串?_Java_Regex_String - Fatal编程技术网

Java-在字符串模式之后将字符串插入另一个字符串?

Java-在字符串模式之后将字符串插入另一个字符串?,java,regex,string,Java,Regex,String,我试图弄清楚如何在原始字符串中的某个字符串模式之后,将一个特定字符串插入另一个字符串(或创建一个新字符串) 例如,给定这个字符串 "&2This is the &6String&f." 如何在所有“&x”字符串之后插入“&l”,使其返回 "&2&lThis is the &6&lString&f&l." 我尝试了下面使用正则表达式的正向查找,但是它返回了一个空字符串,我不知道为什么。“message”变量被传递到方法中

我试图弄清楚如何在原始字符串中的某个字符串模式之后,将一个特定字符串插入另一个字符串(或创建一个新字符串)

例如,给定这个字符串

"&2This is the &6String&f."
如何在所有“&x”字符串之后插入“&l”,使其返回

"&2&lThis is the &6&lString&f&l."
我尝试了下面使用正则表达式的正向查找,但是它返回了一个空字符串,我不知道为什么。“message”变量被传递到方法中

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

    String newMessage = "";

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

    System.out.print(newMessage);
String[]segments=message.split((?您可以使用:

message.replaceAll("(&.)", "$1&l")
  • (&.)
    查找符号(
    &
    )后跟任何符号的模式。(
    &x
    ,如您所写)
  • $1&l
    表示将捕获的组替换为捕获的组本身,然后是
    &l
代码

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

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

我的答案与上面的答案类似,只是这样在很多情况下都可以重用和定制

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

我可能做错了什么,但这对我不起作用。它只是返回了原始字符串。我尝试了:
string newMessage=message.replaceAll((&.),“$1&l”);
System.out.print(newMessage)
@BlackBeltPanda我已经编译了这个代码。你可以在这里查看一下:你确定你没有打印
消息
而不是
新消息
?是的,我尝试打印这两个消息以比较它们,它们看起来是一样的。它输出:
原始消息:&b[&3Obsidian&aAuctions&b]&5&cattension,拍卖开始了!
新消息:&b[&3Obsidian&aAuctions&b]&5&cattension,拍卖开始了!
就像它不想匹配正则表达式一样。@BlackBeltPanda你能编辑你的问题并提供答案吗。实际上,你刚刚找到答案。另一种方法是将“&”改为“§”所以我修改了正则表达式以查找“(§.”并替换为“$1§l”。谢谢!