Jeets
Jeets

Reputation: 3367

Regex to match a word but not another word

I need a regex which matches a string if it starts with http://www.xyzabc.com but the string should not contain the word "getJobId".

For example:

http://www.xyzabc.com/abc          <--- should return true 
http://www.xyzabc.com/getJobId=9   <--- should return false

I tried with the following regex:

^(http://www\.xyzabc\.com)((?!getJobId).)*$

but it did not work. Could anyone suggest?

Upvotes: 1

Views: 2460

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200148

I just took your code and ran it (removing redundant parens and anchors):

final String regex = "http://www\\.xyzabc\\.com((?!getJobId).)*";
System.out.println("http://www.xyzabc.com".matches(regex));
System.out.println("http://www.xyzabc.com/abc".matches(regex));
System.out.println("http://www.xyzabc.com/getJobId=9".matches(regex));

prints

true
true
false

Seems like exactly what you want, doesn't it?

Update

In your edited answer you've got single backslashes instead of double ones.

Upvotes: 2

burning_LEGION
burning_LEGION

Reputation: 13450

use this regex http://www\.xyzabc\.com((?!getJobId)\S)*(?=\s|$)

http://www\.xyzabc\.com silded const

((?!getJobId)\S)* doesn't contain getJobId but able to have symbols

(?=\s|$) next symbol space or match is last word

Upvotes: 0

Anirudha
Anirudha

Reputation: 32797

A much better regex would be

^(http://www.xyzabc.com)(?!.*?getJobId).*$

(?!.*?getJobId) would check if getJobId exits and if it does then it would not match!

Upvotes: 1

Related Questions