You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中按}--{分割字符串并保留大括号的实现方法

Answer

Absolutely, you can achieve this in Java using regex lookarounds—they’re ideal for splitting on a specific sequence without consuming the surrounding characters you need to retain.

The Solution

The key is to target the -- sequence only when it’s directly between a } and a {. We can use positive lookbehind and positive lookahead assertions to do this, which let us check for those surrounding braces without including them in the split match.

Here’s a working code example:

public class SplitExample {
    public static void main(String[] args) {
        String input = "{this}--{is}--{an}--{example}";
        // Split on "--" that comes right after "}" and right before "{"
        String[] splitResult = input.split("(?<=})--(?={)");
        
        // Print the result to verify
        for (String part : splitResult) {
            System.out.println(part);
        }
    }
}

Running this will output exactly what you want:

{this}
{is}
{an}
{example}

How the Regex Works

Let’s break down the regex (?<=})--(?={):

  • (?<=}): This is a positive lookbehind—it checks that the character immediately before the -- is a }, but doesn’t include the } in the part we split on. So the } stays attached to the preceding element.
  • --: The literal sequence we want to split at.
  • (?={): This is a positive lookahead—it checks that the character immediately after the -- is a {, again not including the { in the split match. So the { stays attached to the next element.

Handling Elements with -- Inside

This approach works even if your elements contain -- themselves. For example, if your input is {this--is}--{another--example}, splitting with the same regex will give you:

{this--is}
{another--example}

Because the regex only matches -- that are between } and {, ignoring any -- inside the braces.

内容的提问来源于stack exchange,提问作者Addie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:27:19