简体   繁体   English

从字符串中提取数字(Regex C ++)

[英]Extract numbers from string (Regex C++)

let's say i hve a string S = "1 this is a number=200; Val+54 4class find57" 假设我有一个字符串S = "1 this is a number=200; Val+54 4class find57"

i want to use Regex to extract only this numbers: 我想使用正则Regex仅提取此数字:

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

and not the 4 in "4class" or 57 in "find57" which means only numbers that are surrounded by Operators or space . 而不是“ 4class”中的4或“ find57”中的57,这意味着只有被Operatorsspace包围的数字。 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());

                        } 

by the way i'am using c++ Builder XE6. 顺便说一句,我正在使用c++ Builder XE6.

Just use word boundaries. 只需使用单词边界即可。 \\b matches between a word character and a non-word character. \\b在单词字符和非单词字符之间匹配。

\b\d+\b

OR 要么

\b[0-9]+\b

DEMO 演示

Escape the backslash one more time if necessary like \\\\b\\\\d+\\\\b or \\\\b[0-9]+\\\\b 如有必要,请再次转义反斜杠一次,例如\\\\b\\\\d+\\\\b\\\\b[0-9]+\\\\b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM