Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串中提取前3个数字_Python_Regex - Fatal编程技术网

Python 从字符串中提取前3个数字

Python 从字符串中提取前3个数字,python,regex,Python,Regex,如何提取字符串的前3个数字: 在: “邮箱123(编号)456” 输出: 123只需搜索\d{3}并获取第一个匹配项: match = re.search(r'\d{3}', inputstring) if match: print match.group(0) 演示: 请注意,上面的内容也与子字符串匹配;如果你有一个四位数的数字,它将匹配该数字的前三位数 你的帖子在细节上非常稀疏;假设上面的内容还不够,但您的数字由空格分隔,那么您可以使用\b定位点精确匹配3位数字: match =

如何提取字符串的前3个数字:

在:

“邮箱123(编号)456”

输出:


123

只需搜索
\d{3}
并获取第一个匹配项:

match = re.search(r'\d{3}', inputstring)
if match:
    print match.group(0)
演示:

请注意,上面的内容也与子字符串匹配;如果你有一个四位数的数字,它将匹配该数字的前三位数

你的帖子在细节上非常稀疏;假设上面的内容还不够,但您的数字由空格分隔,那么您可以使用
\b
定位点精确匹配3位数字:

match = re.search(r'\b\d{3}\b', inputstring)
在非单词字符之间仅匹配3位数字(字符串的开头或结尾、空格、标点符号等。任何内容都不是字母、数字或下划线):

重新搜索(r'\b\d{3}\b',输入字符串) >>>检索(r'\b\d{3}\b',“框1234”) >>>检索(r'\b\d{3}\b',“框123”)
更重要的是,如果输入的是
“框1234(编号)567”
?是数字还是数字?如果输入是
A 1 BEE 23参见42 D
match
不是
re.match
,但使用混淆的名称不是一个好的做法,anyway@eyquem:这是一个MatchObject引用,其名称非常常用。“错误不会因为成倍传播而成为事实”甘地。
match = re.search(r'\b\d{3}\b', inputstring)
>>> re.search(r'\b\d{3}\b', inputstring)
<_sre.SRE_Match object at 0x106c4f100>
>>> re.search(r'\b\d{3}\b', "Box 1234")
>>> re.search(r'\b\d{3}\b', "Box 123")
<_sre.SRE_Match object at 0x106c4f1d0>