Vinod
Vinod

Reputation: 294

Create regex for find statement that starts and ends with specific string, except a specific string

I tried a lot but unable to find exact regex.

String str = "this cat is small. dog is pet anmial. this mouse is small.this toy is small. this is a cat and it's small. this is dog and it's small.  ";
Pattern ptr = Pattern.compile("this.*((?!(cat).)*).*small");

I want to extract strings, string starting with this ending with small and should not contain cat anywhere between ,Its not getting the desire output using this regex.

my desire output is :

                this mouse is small
                this toy is small  
                this is dog and it's small

Upvotes: 1

Views: 100

Answers (3)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

String str = "this cat is small. dog is pet anmial. this mouse is small.this toy is small.";
Pattern ptr = Pattern.compile("this\\s(?!cat).*?small");
Matcher matcher=ptr.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Output:

this mouse is small
this toy is small

this\\s(?!cat).*?small : start with this and ends with small

(?!cat) : match if no cat is ahead

.*? : matches any character , as few times as possible

RegexDemo


Update :

Regex demo this((?!cat).)*?small

Output :

this mouse is small
this toy is small
this is dog and it's small

(?!cat). : it will match any character till line break

Upvotes: 4

jitendra varshney
jitendra varshney

Reputation: 3562

use this

   String str = "this cat is small. dog is pet anmial. this mouse is    small.this toy is small.";
   Pattern .compile(^this.*\bsmall);

or

   Pattern .compile(^this.*small$);

Upvotes: 0

Kiran Kumar
Kiran Kumar

Reputation: 1051

Try using

String input = "this mouse is small this toy is small";
boolean matches = input.matches("^This.*small$");

Upvotes: -1

Related Questions