A.R.H
A.R.H

Reputation: 391

Java Regex: Grouping is not right

I Wanna check the validity of a string then try to split it using regex.

The regex should group the input by ";" and each group should be a key-value pair,but my regex group the inputs wrong,where is the problem with my regex?

Here is my function that uses regex:

    public static boolean verify(String str) {
    String pattern = "^(Eval:)+((.+?)=(([^;]*$)))+";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(str);
    if(m.matches()){
        return true;
    }else{
        return false;
    }
}

Valid Examples:

Eval:tag=val;tag2=

Eval:tag=val;tag2=val2

Eval:tag=

Eval:tag=;tag2=

Invalid Examples:

Eval:tag=;tag2=;

Eval:tag;tag2=;

Eval:tag=tag2=

Upvotes: 0

Views: 47

Answers (1)

teppic
teppic

Reputation: 7286

This works:

^Eval:((([^=;]+)=([^=;]*));?)+(?<!;)$

It's basically the same as your attempt, but with a negative look-behind for ; at the end to block the trailing semicolon.

  • Header Eval:
  • Tag= ([^=;]+)=
  • Optional Value ([^=;]*)
  • Semi colon delimited Tag=Value list ((([^=;]+)=([^=;]*));?)+
  • Can't end with a semi-colon (?<!;)$

Upvotes: 1

Related Questions