Nopiforyou
Nopiforyou

Reputation: 350

regex pattern matching in java

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

Upvotes: 0

Views: 1921

Answers (1)

npinti
npinti

Reputation: 52185

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.

Upvotes: 4

Related Questions