簡體   English   中英

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

[英]Extract string using regex

如何從字符串中提取內容( how are you ):

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">how are you</string>. 

我可以使用正則表達式嗎? 如果可能的話,適合它的正則表達式。

注意:我不想使用split函數來提取結果。 你也可以建議一些初學者學習正則表達式的鏈接。

我使用的是python2.7.2

可以使用正則表達式( 如Joey演示 )。

但是,如果您的XML文檔比這個單行文件更大,那么您就無法使用XML,因為XML不是常規語言

使用BeautifulSoup (或其他XML解析器 )代替:

>>> from BeautifulSoup import BeautifulSoup
>>> xml_as_str = '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">how are you</string>. '
>>> soup = BeautifulSoup(xml_as_str)
>>> print soup.text
how are you.

要么...

>>> for string_tag in soup.findAll('string'):
...     print string_tag.text
... 
how are you
(?<=<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">)[^<]+(?=</string>)

會匹配你想要的東西,作為一個簡單的例子。

(?<=<)[^<]+

也會。 這完全取決於您的輸入的格式。

嘗試使用以下正則表達式:

/<[^>]*>(.*?)</

這將匹配通用HTML標記(將“string”替換為您要匹配的標記):

/<string[^<]*>(.*?)<\/string>/i

(i =不區分大小寫)

暫無
暫無

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

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