Java中按}--{分割字符串并保留大括号的实现方法
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

