Ramesh
Ramesh

Reputation: 2337

Regex to match pattern with subdomain in java gives issues

I am trying to match the sub domain of an url using http://([a-z0-9]*.)?example.com/.* which works perfectly for these cases.

http://example.com/index.html
http://test.example.com/index.html
http://test1.example.com/index.html
http://www.example.com/122/index.html

But the problem is it matches for this URL too. http://www.test.com/?q=http://example.com/index.html

if an URL with another domain has the URL in path it matches.Can any one tell me how to match for current domain only. getting the host will work but i need to match full URL.

Upvotes: 0

Views: 823

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336368

Are you aware that . matches any character?

If you use the regex

http://([a-z0-9]*\.)?example\.com/.*

(or, as a Java String)

"http://([a-z0-9]*\\.)?example\\.com/.*"

it should work because now the ?q= part won't be matched.

This assumes that you're using the .matches() method which forces the entire string to match. Otherwise, add a ^ at the start of the regex.

Upvotes: 3

someonelse
someonelse

Reputation: 260

simplest way would be:

^http://([a-z0-9]*?\.)?example\.com/.*

the ^ matches the starting position within the string. Dont confuse it with [^ ] though.

Upvotes: 1

Related Questions