tags:

views:

78

answers:

4

Hi

I have the following urls:

www.localhost.com
localhost.com
test.localhost.com

How would I match match www or nothing in a regex?

Thanks, Andy

+2  A: 
(?:www)?

should match www or nothing.

gameover
You mean /www|nothing/ :p
KennyTM
What does the "?:" before "www" do?
stiank81
It is for grouping *only*
gameover
`(abc)` is capturing, `(?:abc)` is grouping without capturing. See http://www.regular-expressions.info/brackets.html
KennyTM
Thx for clearing that up :-)
stiank81
One thing to note though, is it still will not match localhost.com, you'll need to ignore the dot afterwards also.
William
This will match www anywhere in the string, such as examplewww.com
BlueRaja - Danny Pflughoeft
A: 

If I understand your question correctly, you need to use a lookahead, like this:

/^www(?=\.localhost.com)/

This will match www if and only if it's followed by .localhost.com.

If that's not what you're trying to do, please clarify.

SLaks
This won’t match anything because you can’t match a `.localhost.com` after the end of the string.
Gumbo
@Gumbo: Fixed; thanks.
SLaks
A: 

www.+? It matches all string that has prefix as www

Daniel
A: 

/^www/ alows you to check if subjects starts with www.

hsz