Python正则表达式从字符串获取URL

时间:2013-06-14 23:45:05

标签: python regex

我正在使用正则表达式从字符串中获取URL

这是我的代码:

import re

class ProcessWebsite(object):

    def __init__(self, *args, **kwargs):
        print "Test"

    def set_orden(self, command):
        self.command = command
        return self.getURL()

    def getURL(self):
        regex = re.compile("([0-9A-Za-z]{2,}\.[0-9A-Za-z]{2,3}\.[0-9A-Za-z]{2,3}|[0-9A-Za-z]{2,}\.[0-9A-Za-z]{2,3})$")
        return regex.findall(str(self.command))

我从这里调用方法“getURL”:

# -*- coding: utf-8 -*-
import Tkinter as tk
import tkFont
from Tkinter import StringVar
from Tkinter import Label
from processor.processwebsite import ProcessWebsite



def changeText(newText):
    var.set(newText)

def on_return_release(event):
    pr = ProcessWebsite()
    changeText(pr.set_orden(text.get("1.0", "end")))



app = tk.Tk()

var = StringVar()
label = Label(app, textvariable=var) 
font = tkFont.Font(family='Helvetica', size=36, weight='bold')
label.pack()

text = tk.Text(app, width=50, font=font)
text.config(width=35, height=2)
text.pack()
text.bind("<KeyRelease-Return>", on_return_release)

app.mainloop()

这会返回“无”,但如果我更改方法“getURL”的这一行,那么它可以正常工作

def getURL(self):
        regex = re.compile("([0-9A-Za-z]{2,}\.[0-9A-Za-z]{2,3}\.[0-9A-Za-z]{2,3}|[0-9A-Za-z]{2,}\.[0-9A-Za-z]{2,3})$")
        return regex.findall("Test with google.com")

有谁知道会发生什么?

由于

1 个答案:

答案 0 :(得分:3)

看起来文本选择不适用于.get(1.0, 'end'),这可能是由于在您阅读之前添加了换行符。

我不做Python太多,也许有更好的方法,但这没关系:

text.get('1.0', 'end -1 chars')

或者,只获取第一行的文字:

text.get('1.0', '1.end')