0

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=

7
  • 1
    You forgot to ask a question. Commented Sep 25, 2017 at 1:45
  • @shmosel you're right! Commented Sep 25, 2017 at 1:46
  • 1
    Eval:tag=;tag2= <-- is this really valid? I would hate to be the person who is working with your data if this be the case. Commented Sep 25, 2017 at 1:47
  • 1
    Btw, you can replace the whole method with str.matches("^(Eval:)+((.+?)=(([^;]*$)))+") Commented Sep 25, 2017 at 1:48
  • 1
    The regex you are looking for is extremely complex. Are you certain that rfc6265 does not already have libraries in Java to handle this? Commented Sep 25, 2017 at 2:02

1 Answer 1

1

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 (?<!;)$
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.