gpt4 book ai didi

python - 正则表达式 Findall 在 Linux 中挂起

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:47 24 4
gpt4 key购买 nike

我编写了一个程序,使用 re.findall 在字符串中查找 float ,如下所示:

string1 = 'Voltage = 3.0 - 4.0 V'
string2 = '3.66666'

float1 = re.findall('\d+.\d+', string1)
float2 = re.findall('\d+.\d+', string2)

这个程序在 Windows 上运行良好,但是当我尝试在 Linux 上运行该程序时,程序一直卡在第二个 re.findall 上。知道是什么导致了这个问题吗?如何解决?

谢谢

最佳答案

您需要将正则表达式定义为原始字符串,并且还需要对点进行转义。点是正则表达式中的一个特殊元字符,它匹配除换行符以外的任何字符。转义正则表达式中的点将匹配文字点。

float1 = re.findall(r'\d+\.\d+', string1)
float2 = re.findall(r'\d+\.\d+', string2)

From re doc .

Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\' as the pattern string, because the regular expression must be \, and each backslash must be expressed as \ inside a regular Python string literal.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

>>> string1 = 'Voltage = 3.0 - 4.0 V'
>>> string2 = '3.66666'
>>> float1 = re.findall(r'\d+\.\d+', string1)
>>> float2 = re.findall(r'\d+\.\d+', string2)
>>> float1
['3.0', '4.0']
>>> float2
['3.66666']

关于python - 正则表达式 Findall 在 Linux 中挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com