当前位置:首页 > 科技动态 > 正文

如何截取混合字符中的数字

如何截取混合字符中的数字

要截取混合字符中的数字,你可以使用正则表达式(Regular Expression,简称Regex)。以下是一个使用Python语言的例子,它展示了如何使用正则表达式来...

要截取混合字符中的数字,你可以使用正则表达式(Regular Expression,简称Regex)。以下是一个使用Python语言的例子,它展示了如何使用正则表达式来查找并截取字符串中的所有数字。

```python

import re

def extract_numbers(text):

使用正则表达式匹配所有数字

numbers = re.findall(r'd+', text)

将匹配到的数字转换为整数列表

numbers = [int(num) for num in numbers]

return numbers

示例文本

mixed_text = "Hello 123, this is a test 4567 and some numbers like 890 and 12."

调用函数并打印结果

extracted_numbers = extract_numbers(mixed_text)

print(extracted_numbers)

```

这段代码定义了一个函数`extract_numbers`,它接受一个字符串`text`作为参数,并返回一个包含所有数字的列表。正则表达式`d+`用于匹配一个或多个数字,`re.findall`函数用于查找所有匹配的子串。

运行上述代码,你将得到以下输出:

```

[123, 4567, 890, 12]

```

这表示函数成功从混合字符中提取了所有的数字。

最新文章