请教各位大神,如何判断用户输入的是 www.domain.xxx 还是 domain.xxx?

2014 年 12 月 11 日
 imkh
xxx:表示com,net,info等

domain = raw_input("Please input an domain: ")
if 是www.domain.xxx
执行操作
elif 是domain.xxx:
执行操作
else
执行操作
4568 次点击
所在节点    Python
20 条回复
besto
2014 年 12 月 11 日
nginx完全可以把带3w和不带3w的解到不同的网页上去啊。。。
NathanInMac
2014 年 12 月 11 日
@besto 。。你这完全不看帖的啊,人家是form里面。要用正则

^((?<subdomain>.+?)\.)*(?<domain>[^\.]*)$
oott123
2014 年 12 月 11 日
domain[0:3] == "www"
little_cup
2014 年 12 月 11 日
if domain[:3] == 'www':
xxx
elif '.com' in domain:
yyy
else
zzz
oott123
2014 年 12 月 11 日
不对,应该是domain[0:4] == "www."
imkh
2014 年 12 月 11 日
@NathanInMac 正则还没学,是 m = re.match(r'^((?<subdomain>.+?)\.)*(?<domain>[^\.]*)$','domain') 这样用吗?
imkh
2014 年 12 月 11 日
@little_cup 这样好像不行吧,如果有info,io这些,那岂不是要多次判断?
ericls
2014 年 12 月 11 日
if domain.startswith('www.')
viesong
2014 年 12 月 11 日
正则表达式
viesong
2014 年 12 月 11 日
domain = /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/;
Amit
2014 年 12 月 11 日
@besto 昨天才发现www.v2ex.com和v2ex.com不是一个ip
thedevil5032
2014 年 12 月 11 日
判别字符串开头用 @ericls 提到的 str.startswith, 末尾的话 (xxx) 用 str.endswith.
lll9p
2014 年 12 月 11 日
def info_func(): pass
def com_func(): pass
def net_func(): pass
...
xxx={'info':info_func,'com':com_func,'net':net_func}
domain = raw_input("Please input an domain: ")
if domain.startswith('www'):
执行操作
else:
xxx[domain.split('.')[-1]]()
lll9p
2014 年 12 月 11 日
空格被吃了。。改一下吧
def info_func(): pass
def com_func(): pass
def net_func(): pass
...
xxx={'info':info_func,'com':com_func,'net':net_func}
domain = raw_input("Please input an domain: ")
if domain.startswith('www.'):
执行操作
else:
try:
xxx[domain.split('.')[-1]]()
except:
pass
besto
2014 年 12 月 11 日
@NathanInMac 我把问题想复杂了。。。
4everLoveU
2014 年 12 月 11 日
直接domain[0:4] == 'www.' 不就可以了

楼上越搞越复杂
FrankFang128
2014 年 12 月 11 日
ugly
yangzh
2014 年 12 月 11 日
楼上用正则的,除了炫技似乎也没啥必要
dingyaguang117
2014 年 12 月 11 日
看有几个 . ?
thedevil5032
2014 年 12 月 12 日
@oott123
@little_cup
@4everLoveU

domain[0:4] 和 startswith 的区别在于:

1. domain == '' 的时候, 前者会出现 IndexError 异常. startswith 会返回 False.
2. startswith 的 意图更加明显, 更易读.
3. startswith 会慢一点点.

参考:
http://stackoverflow.com/questions/1315559/how-good-is-startswith

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/153016

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX