【问题标题】:python - regex: we are looking for the input of a functionpython - 正则表达式:我们正在寻找函数的输入
【发布时间】:2017-07-21 22:52:17
【问题描述】:
import re

def step_through_with(s):
    pattern = re.compile(s + ',')
    if pattern == True:
        return True
    else:
        return False

任务是在一个句子中找到一个词,它是函数的输入参数。语法应该如何?

【问题讨论】:

  • pattern == True?
  • 请问参数是怎么传给函数的?或者您想知道如何使用 re 模块进行匹配?
  • 你在搜索什么样的词?请提供全面的示例。

标签: python regex function syntax


【解决方案1】:

如果你想在一个句子中找到一个词,你必须考虑边界(例如,搜索“fun”不会匹配“function”)。

一个例子:

import re

def step_through_with(sentence, word):
    pattern = r'\b{}\b'.format(word)
    if re.search(pattern, sentence):
        return True
    return False


sentence = 'we are looking for the input of a function'

print step_through_with(sentence, 'input')   # True
print step_through_with(sentence, 'fun')     # False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多