如何从 Perl 中的字符串中提取数字? [英] How to extract a number from a string in Perl?

查看:80
本文介绍了如何从 Perl 中的字符串中提取数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

print $str;
abcd*%1234$sdfsd..#d

该字符串将始终只有一段连续的数字,例如在这种情况下的 1234.其余的将是字母或其他特殊字符.

The string would always have only one continuous stretch of numbers, like 1234 in this case. Rest all will be either alphabets or other special characters.

如何提取数字(在本例中为 1234)并将其存储回 str?

How can I extract the number (1234 in this case) and store it back in str?

这个页面建议我应该使用 \d,但是如何?

This page suggests that I should use \d, but how?

推荐答案

$str =~ s/\D//g;

这会从字符串中删除所有非数字字符.这就是您需要做的全部.

This removes all nondigit characters from the string. That's all that you need to do.

如果可能存在其他脚本中的 Unicode 数字,更好的解决方案是:

if Unicode digits in other scripts may be present, a better solution is:

$str =~ s/[^0-9]//g;

这篇关于如何从 Perl 中的字符串中提取数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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