从字符串中提取数字(Regex C ++) [英] Extract numbers from string (Regex C++)

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

问题描述

让我们说一个字符串 S =1这是一个数字= 200; Val + 54 4class find57

我想使用 Regex 只提取这些数字:

i want to use Regex to extract only this numbers:

   num[1] = 1
   num[2] = 200
   num[3] = 54

而不是4class中的4或find57中的57,这意味着只有被运算符空格
i尝试此代码但没有结果:

and not the 4 in "4class" or 57 in "find57" which means only numbers that are surrounded by Operators or space. i tried this code but no results:

std::string str = "1 this is a number=200; Val+54 4class find57";
 boost::regex re("(\\s|\\-|\\*|\\+|\\/|\\=|\\;|\n|$)([0-9]+)(\\s|\\-|\\*|\\+|\\/|\\;|\n|$)");
 boost::sregex_iterator m1(str.begin(), str.end(), re);
 boost::sregex_iterator m2;
 for (; m1 != m2; ++m1) {

    advm1->Lines->Append((*m1)[1].str().c_str());

                        } 

我使用 c ++ Builder XE6。

推荐答案

\b 字词和非字词字符之间的比对。

Just use word boundaries. \b matches between a word character and a non-word character.

\b\d+\b

\b[0-9]+\b


b $ b

DEMO

如果必要,再次转义反斜杠,例如 \\b\\d + \\b \\b [0-9] + \\b

Escape the backslash one more time if necessary like \\b\\d+\\b or \\b[0-9]+\\b

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

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