2

I have a simple program to split a string by regex like so:

public class Main
{
    public static void main(String[] args) {
        String regex = "\\{|\\}|\\+";
        String input = "F-{0000}a{yy}{mm}";

        String [] splitInput = input.split(regex);


        for(int i = 0; i < splitInput.length; i++) {
            System.out.println("Value: " + splitInput[i]);
        }

    }
}

and it prints

Value: 0 A-                                                                                                                                                                                                                                       
Value: 1 0000                                                                                                                                                                                                                                     
Value: 2 a                                                                                                                                                                                                                                        
Value: 3 yy                                                                                                                                                                                                                                       
Value: 4                                                                                                                                                                                                                                          
Value: 5 mm  

I just want it so that my split string does not include value 4 which is the empty character. I know this is happening because the }{ are back to back. My regex I believe just says to split on { or } and I thought the + will split on consecutive delmiters but that doesn't seem to be the case. Any ideas?

1 Answer 1

3

Your regex is incorrect, it will split on {, } or +. What you want is to split on one or more of { or } which you can do with a character class:

String regex = "[{}]+";

Demo on rextester

Sign up to request clarification or add additional context in comments.

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.