【问题标题】:string match using re in python re.search [closed]在python re.search中使用re进行字符串匹配[关闭]
【发布时间】:2014-05-14 09:29:42
【问题描述】:

search() 来匹配字符串。下面是我的代码

import re

s = "hello world"

if re.search(r'hello world other exter string',s):
    print 'match success'
else:
    print 'no match'

在上面的代码中,它没有给我匹配。即使“hellow world”是给定字符串的一部分。我也尝试使用 re.match() 但得到相同的结果。

【问题讨论】:

  • 首先阅读docs。你可以简单地做s in 'hellow world other exter string'
  • 参数顺序错误,但“hello world”永远不会匹配示例字符串(“hello”与“hellow”)。

标签: python regex


【解决方案1】:

你的论点顺序是错误的。应该是re.search(pattern, string):

if re.search(s, 'hello world other exter string'):
    print 'match success'
else:
    print 'no match'

[OUTPUT]
match success

此外,正如@thefourtheye 所说,一个简单的if substring in string: 就足够了。正则表达式用于检测字符串中的模式。比如说你想找到所有 5 个字母的单词(虽然这可以在没有正则表达式的情况下完成):

>>> print re.findall(r'\b[a-zA-Z]{5}\b', 'hello world other exter string')
['hello', 'world', 'other', 'exter']

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多