简体   繁体   中英

Extract numbers from string (Regex C++)

let's say i hve a string S = "1 this is a number=200; Val+54 4class find57"

i want to use Regex to extract only this numbers:

   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 . 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.

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

\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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