0

I want to match a pattern for a string in Java. The format of the string will be like this.

"INSERT %ABC% %DEF%"

I want to be able to take strings ABC and DEF between the two set of '%'

public void parseInput(String input){
    Pattern p = Pattern.compile("?: .* %(.*)%)*");
    Matcher m = p.matcher(input);
    String s1 = m.group(1);
    String s2 = m.group(2);
}

I've played around so far, and continue to get syntax errors. In this case, this has been my most recent attempt, having gotten a dangling meta character error message

1 Answer 1

4

You could use the .find() method which will keep on going through your string and yielding what it finds:

    String str = "INSERT %ABC% %DEF%";
    Pattern p = Pattern.compile("%(.*?)%");
    Matcher m = p.matcher(str);
    while(m.find())
    {
        System.out.println(m.group(1));
    }

Yields:

ABC

DEF

EDIT: Just as an FYI, having a pattern like so: %(.*)%, will make your regular expression greedy, meaning that it will stop matching once it finds the last % (thus yielding ABC% %DEF). Adding the ? operator after the * operator (as per my example) will make your pattern non greedy, and it will stop at the first % it finds.

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

2 Comments

Ahh thank you! That works quite well. Also didn't know about the difference between greedy and non greedy regular expressions
@Nopiforyou: You're welcome. Greediness is something you need to keep an eye out when using the * and + operators.

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.