簡體   English   中英

如何匹配某個單詞后的所有內容

[英]How to match everything after a certain word

您好,我正在嘗試匹配“http:”之后的所有內容並擺脫它。

示例字符串如:

在阿肯色州發現的新魚種 http://t.co/E218nP6DZd

在阿肯色州發現的一種新魚 ( PIGFISH ) http://t.co/qqoMmHVItg

預期結果:

在阿肯色州發現的新魚種

在阿肯色州發現的一種新魚 ( PIGFISH )

謝謝 :)

解決此問題的另一種方法是拆分目標單詞上的字符串並返回第一部分。

my_string="New species of fish found at Arkansas http://example"
print(my_string.split("http",1)[0])
#New species of fish found at Arkansas 

您可以對字符串調用index()函數,該函數將返回傳入的子字符串第一次出現的索引。 您可以使用它來直接切片您想要的部分:

s = "New species of fish found at Arkansas http: //example.com/E218nP6DZd"

s[:s.index('http')]
# 'New species of fish found at Arkansas '

您需要一個正則表達式來捕獲http之前的內容,您可以使用search/match並打印捕獲組,或使用findall ,您將得到相同的結果

values = ["New species of fish found at Arkansas http: //urlshorten",
          "A new fish discovered in Arkansas ( PIGFISH ) http: //urlshorten"]

reg = re.compile("(.*)http")
for value in values:
    txt = reg.findall(value)
    print(txt)

    txt = reg.search(value) # or match
    print(txt.groups())
import re

web_string = 'A new fish discovered in Arkansas ( PIGFISH ) http: //website.com/qqoMmHVItg'
match_group = re.match('(.*\( PIGFISH \)) (http.*$)', web_string)

no_http_string = match_group[1]
print(no_http_string)

應該讓你

A new fish discovered in Arkansas ( PIGFISH )

您始終可以使用正則表達式來匹配 url。

import re
if text.search("http"):
    #code

正如azro所說,更容易捕獲“http:”之前的內容,而忽略其余部分。

這是我嘗試使用re包捕獲( ... )字符串開頭的任何字母數字\\w或空格\\s的正則表達式,但文本“http”和之后的任何數量的任何類型的字符.*是不包括在捕獲組中。

([\w\s]*)http.*

[\\w\\s]*匹配任意數量的字母數字或空格

()包括在捕獲組中

http.*匹配確切的文本“http”和之后的任意數量的任何字符。

這是我在你的字符串上運行的 python 代碼:

s = "New species of fish found at Arkansas https://twitter.com/oliviadodson_/status/445043948969398272/photo/1"
>>> import re
>>> pat = re.compile(  r'([\w\s]*)http.*'  )
>>> m = pat.search( s ); print(m)
>>> m.group(1)
'New species of fish found at Arkansas '

這一次僅適用於文本的一行(不包括末尾的換行符)。 您可以修改它以適合您的確切用例,例如在捕獲中包含標點符號等。使用for循環遍歷段落等。

暫無
暫無

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

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