regexp自动在函数输入上运行? [英] regexp automatically runs on function input?

查看:65
本文介绍了regexp自动在函数输入上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我已经搜索了一段时间,却找不到任何东西,因此,我决定寻求SO方面的专家来帮助我弄清正在发生的事情.

So, I've searched for a while and couldn't find anything, so I've decided to turn to the experts on SO to help me clarify what is going on.

我正在学习Python,并在学习正则表达式的同时,遇到了一些我不太想知道的有趣语法.在此示例中,定义了一个函数,该函数在输入参数上运行正则表达式,将整数的匹配返回为浮点数,或者如果输入与看起来像数字的东西不匹配,则引发异常:

I am learning Python and whilst learning about regular expressions, I've come across an interesting bit of syntax that I can't quite figure out. In this example, a function is defined which runs a regular expression on the input parameter, returning the match of the integer as a float, or throwing an exception if the input doesn't match something that looks like a number:

import re
def getNumber(token):
  r'-?[1-9][0-9]*.?[0-9]*'
  return float(token)

该函数可以这样调用:

print getNumber('123.123')
print getNumber('123.123')+40

它将输出:

123.123
163.123

我试图了解这种情况的发生机理.我知道我们正在通过调用r'STRING'声明一个正则表达式对象,但是以某种方式声明正则表达式也会导致token参数也传递到表达式中.这是具有明确包含名为"token"的参数的函数的特征吗?是否存在与多个参数关联的行为?显然,这里已经完成了一些工作来提供pythonic语法,我只想知道它如何工作以及将来如何使用它的细节.将我指向文档将是很棒的,因为我在该主题上找不到任何东西.

I am trying to understand the mechanics of how this is happening. I understand that we are declaring a regular expression object with the call to r'STRING', but somehow just declaring that regular expression causes the token parameter to get passed into the expression as well. Is this a trait with functions explicitly containing a parameter called "token"? Is there a behavior associated with multiple parameters? It definitely seems that some work has been done here to provide a pythonic syntax, I would just like to know the details of how it works and how to use it in the future. Pointing me to documentation would be great, as I couldn't find anything on the subject.

推荐答案

此函数未在输入上运行正则表达式...它正在对输入进行调用 float 来转换输入到一个浮点数.函数中的正则表达式"只不过是一个文档字符串.

This function isn't running a regular expression on the input ... It's calling float on the input which is converting the input to a floating point number. The "regular expression" that is there is nothing more than a docstring on the function.

请注意, r这是一个字符串" 只是创建一个与正则表达式无关的原始字符串"("\ t" 是制表符,而 r"\ t" 是文字字符'\''t').

Note that r"this is a string" simply creates a "raw string" which has nothing to do with regex ("\t" is tab whereas r"\t" is the literal characters '\' and 't') .

这篇关于regexp自动在函数输入上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆