PraveenM
PraveenM

Reputation: 23

Regular Expression to match a list of strings and ignore a list of strings

I am looking for a regular expression that meets the below requirement

  1. Ignore all the strings that starts with zzTest
  2. Match all the strings that contains the word rest and not started with zzTest

Input Strings:

zzTest.docs:service1
zzTest.rest:service2
Regression.rest:service1
Regression.docs.service2 

Expected output:

Regression.rest:service1

Tried with the regular expression \s*(?!\w*(zzTest)\w*)\w*(rest)\w*\s* Its works when there is no dot(.) in the input String

Any help appreciated

Upvotes: 1

Views: 1174

Answers (2)

JeremyJi
JeremyJi

Reputation: 101

Try this:

stringList.stream().filter(s -> !s.startsWith("zzTest")).filter(s -> s.contains("rest"));

Although this is not a regular expression solution.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You may use

s.matches("(?!zzTest).*rest.*")

The pattern will work as follows:

  • ^ - start of string (implicit in matches)
  • (?!zzTest) - not starting with zzTest
  • .*rest.* - any 0+ chars other than line break chars, as many as possible, up to the last rest in the line, and then the rest of the line.
  • $ - (implicit in matches()): end of string.

To match the whole string, add (?s) at the start of the pattern.

To extend it, use alternations:

s.matches("(?!zzTest|yyTest|etc).*(?:rest|more here).*")

To add whole word matching support, use \b around the words:

s.matches("(?!\\b(?:zzTest|yyTest|etc)\\b).*\\b(?:rest|more here)\\b.*")

Upvotes: 2

Related Questions