需要Python正则表达式来提取URL的最后两个单词
请推荐正则表达式从URL中提取最后两个单词,如:需要Python正则表达式来提取URL的最后两个单词,python,regex,url,Python,Regex,Url,请推荐正则表达式从URL中提取最后两个单词,如: INPUT OUTPUT 'www.abcd.google.com' --> 'google.com' 'www.xyz.stackoverflow.com' --> 'stackoverflow.com' 与一起用作delimeter: url_strings = 'www.xyz.stackoverflow.com' s = '.'.joi
INPUT OUTPUT
'www.abcd.google.com' --> 'google.com'
'www.xyz.stackoverflow.com' --> 'stackoverflow.com'
与
一起用作delimeter:
url_strings = 'www.xyz.stackoverflow.com'
s = '.'.join(url_strings.split('.')[-2:])
# stackoverflow.com
print(s)
如果需要输入验证:
url_strings = 'www.xyz.stackoverflow.com'
def return_last_words(url_string, last_words_count=2):
splitted = url_string.split('.')
if last_words_count < len(splitted):
return '.'.join(splitted[-last_words_count:])
return url_string
print(return_last_words(url_strings))
url\u strings='www.xyz.stackoverflow.com'
def return\u last\u words(url\u字符串,last\u words\u count=2):
splitted=url_string.split('.'))
如果最后的单词数
将此正则表达式与“负前瞻”功能一起使用:
import re
for url in ['www.abcd.google.com','www.xyz.stackoverflow.com']:
print (re.search (r'\w*\.(?!\w*\.)\w*', url)[0])
google.com
stackoverflow.com
:欢迎使用堆栈溢出!请拿下,阅读,并提供。“为我实现此功能”是本网站的主题。你必须做一个诚实的尝试,然后问一个关于你的算法或技术的具体问题。为什么是正则表达式?str.split()在大多数情况下都更容易在jordanmThnx一吨的时候使用;完全符合我的regex要求…thnx作为regex的替代…Welcome@Rubous请标记为已解决:)