Linus_30
Linus_30

Reputation: 191

regex to match a string only if a substring is not present

str = "sysparm_type=list_data&count=20&start=0&p=incident%3Bq%3Aactive%3Dtrue%5Epriority%3D1%5EEQ&table=incident"

I've written a regex for the above string but i want to match it only if the "priority" substring is not present. Here's my regex:

.*sysparm_type=list_data&count=(\d+)&start=(\d+)&p=incident.*active.*true^((?!priority).)*$&table=incident

But this part ^((?!priority).)*$ of the regex isn't working.

Upvotes: 0

Views: 820

Answers (3)

ursa
ursa

Reputation: 4591

(a) regexp is bad solution for query string parsing - slow, memory consuming, error prone

(b) try to use any existing library for this task, e.g. apache commons:

String str = "sysparm_type=list_data&count=20&start=0&p=incident%3Bq%3Aactive%3Dtrue%5Epriority%3D1%5EEQ&table=incident";
List<NameValuePair> pairs = URLEncodedUtils.parse(str, StandardCharsets.UTF8)
for (NameValuePair pair : pairs)
    if (pair.getName().equals("priority"))
        return; // do nothing

Upvotes: 1

Saravana
Saravana

Reputation: 12817

If you want to check subString a simple solution will be checking str.indexOf(subString) will return a int if it's greater than 0 then str contains subString.

If you want to do it in regExp use the pattern .*priority.*, you can some more restriction of the substring if you're sure about its occurrences and position

Upvotes: 0

Reenactor Rob
Reenactor Rob

Reputation: 1526

Caret ^ and $ match at the beginning and end of the entire string. Very greedy.

Wouldn't it be simpler, easier to read and maintain if you just checked for the profile string to be present?

    String pattern = "((?!priority).)*";  <== pasted from above, prob not valid regex

  // Create a Pattern object
  Pattern r = Pattern.compile(pattern);

  // Now create matcher object.
  Matcher m = r.matcher(line);
  if (m.find( )) {
    System.out.println("Found value" );

  } else {
     System.out.println("NO MATCH");
  }

Upvotes: 1

Related Questions