繁体   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