我不擅长正则表达式,但我相信 ^(http://)?+((.{0,2}[^w])|(.{3}[^.]))
可以完成你想要的:
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));
产生这个输出:
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
由于我不认为自己擅长正则表达式,因此我不会说这是万无一失的,但它适用于您的示例字符串以及我测试过的一些更难的字符串。