Reputation: 3800
I need to check a URL string, and if the URL does not contain "www.", insert it in the correct position.
For example, the strings on the left should be transformed as indicated:
www.myweb.com => www.myweb.com
myweb.com => www.myweb.com
http://myweb.com => http://www.myweb.com or www.myweb.com
http://www.myweb.com => http://www.myweb.com or www.myweb.com
Upvotes: 0
Views: 155
Reputation: 34051
I'm not great with regular expressions, but I believe ^(http://)?+((.{0,2}[^w])|(.{3}[^.]))
accomplishes what you want:
String s1 = "www.myweb.com";
String s2 = "myweb.com";
String s3 = "http://myweb.com";
String s4 = "http://www.myweb.com";
String pattern = "^(http://)?+((.{0,2}[^w])|(.{3}[^.]))";
String www = "$1www.$2";
System.out.println(s1 + " -> " + s1.replaceFirst(pattern, www));
System.out.println(s2 + " -> " + s2.replaceFirst(pattern, www));
System.out.println(s3 + " -> " + s3.replaceFirst(pattern, www));
System.out.println(s4 + " -> " + s4.replaceFirst(pattern, www));
produces this output:
www.myweb.com -> www.myweb.com
myweb.com -> www.myweb.com
http://myweb.com -> http://www.myweb.com
http://www.myweb.com -> http://www.myweb.com
Since I don't consider myself strong with regular expressions, I'm not going to say this is foolproof, but it works on your example strings and on some tougher ones I tested it with.
Upvotes: 2
Reputation: 132992
try as:
if(!str.contains("www")){
if(str.contains("://"))
str=str.replace("://","://www.");
else
str="www."+str;
}
Upvotes: 0