繁体   English   中英

在正则表达式模式 python 中使用动态 int 变量

[英]use dynamic int variable inside regex pattern python

我刚开始学习 python,抱歉,如果这个问题已经被问过。

我在这里写是因为那些对我没有帮助,我的要求是读取文件并打印其中的所有 URL。在 for 循环中,我使用的正则表达式模式是[^https://][\w\W]* ,效果很好。 但我想知道我是否可以动态传递 https:// 之后的行长度并获得 output 出现而不是*

我试过[^https://][\w\W]{var}} where var=len(line)-len(https://)

这些是我尝试过的其他一些模式

pattern = '[^https://][\w\W]{'+str(int(var))+'}'

pattern = r'[^https://][\w\W]{{}}'.format(var)

pattern = r'[^https://][\w\W]{%s}'%var

我可能误解了您的问题,但如果您知道 url 始终以https://开头,那么这将是前八个字符。 然后你可以在找到url后得到长度:

# Example of list containing urls - you should fill that with your for loop
list_urls = ['https://stackoverflow.com/questions/61006253/use-dynamic-int-variable-inside-regex-pattern-python', 'https://google.com', 'https://stackoverflow.com']
for url in list_urls:
    print(url[8:])

出去

stackoverflow.com/questions/61006253/use-dynamic-int-variable-inside-regex-pattern-python
google.com
stackoverflow.com

您可以使用re.findall找到所有 url,而不是 for 循环

import re

url_pattern = "((https:\/\/)([\w-]+\.)+[\w-]+[.+]+([\w%\/~\+#]*))"
# text referes to your document, that should be read before this
urls = re.findall(url_pattern, text)

# Using list comprehensions
# Get the unique urls by using set
# Only get text after https:// using [8:]
# Only parse the first element of the group that is returned by re.findall using [0]
unique_urls = list(set([x[0][8:] for x in urls]))

# print the urls
print(unique_urls)

在您的模式中,您使用[^https://]这是一个否定字符 class [^它将匹配除列出的任何字符。

一种选择是使用文字字符串插值。 假设您的链接不包含空格,您可以使用\S而不是[\w\W] ,因为后一种变体将匹配任何字符,包括空格和换行符。

\bhttps://\S{{{var}}}(?!\S)

正则表达式演示

最后的断言(?!\S)是一个空白边界,以防止部分匹配,而单词边界\b将防止 http 成为更大单词的一部分。

Python 演示

例如

import re
line = "https://www.test.com"
lines = "https://www.test.com https://thisisatestt https://www.dontmatchme"

var=len(line)-len('https://')
pattern = rf"\bhttps://\S{{{var}}}(?!\S)"

print(re.findall(pattern, lines))

Output

['https://www.test.com', 'https://thisisatestt']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM