簡體   English   中英

在Python中使用正則表達式提取字符串

[英]Extract string using regex in Python

我在如何基於正則表達式提取(即分配給變量)字符串方面有些掙扎。 我已經解決了正則表達式-我在正則表達式上進行了測試。 但是我迷失了如何在Python中實際實現它。 我的正則表達式字符串是:

http://jenkins.mycompany.com/job/[^\s]+

我想做的是獲取字符串,如果其中有一個與正則表達式匹配的模式,則將整個“模式”放入變量中。 因此,例如,給定以下字符串:

There is a problem with http://jenkins.mycompany.com/job/app/4567. We should fix this.

我想提取http://jenkins.mycompany.com/job/app/4567並為其分配一個變量。 我知道我應該使用re,但是我不確定我是否想要re.match或re.search以及如何獲得想要的東西。 任何幫助或指針將不勝感激。

import re
p = re.compile('http://jenkins.mycompany.com/job/[^\s]+')
line = 'There is a problem with http://jenkins.mycompany.com/job/app/4567. We   should fix this.'
result = p.search(line)
print result.group(0)

輸出:

http://jenkins.mycompany.com/job/app/4567.

使用re.findall方法選擇字符串中的第一個找到的匹配項:

re.findall(pattern_string, input_string)[0] # pick the first match that is found

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM