Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: find integer but not float

Tags:

c++

c#

regex

stl

I want a regex pattern to find any integer in the string, but not float (with decimal point as "." or ",". So for string:

abc111.222dfg333hfg44.55

it should only find:

333

I created regex pattern:

(?<!\\d[\\.,]|\\d)\\d+(?![\\.,]\\d+|\\d)

but it fails when using in C++ STL regex. It throws exception:

Unhandled exception at at 0x76AF4598 in xxxxxx.exe: Microsoft C++ exception: std::regex_error at memory location 0x00C1F218.

but it works nice in C# Regex class

UPDATE:

My Code:

smatch intMatch;
regex e1("(?<!\\d[\\.,]|\\d)\\d+(?![\\.,]\\d+|\\d)");
string s("111.222dfg333hfg44.55");
regex_search ( s, intMatch, e1 );

but it throws exception on the line:

regex e1("(?<!\\d[\\.,]|\\d)\\d+(?![\\.,]\\d+|\\d)");

UPDATE 2:

Both answers are correct, but for C++ STL regex Toto one works better.

like image 231
user3057544 Avatar asked Sep 20 '15 08:09

user3057544


1 Answers

I'm not sure for C++ STL, but many regex flavors don't support variable length negative lookbehind.

In your case you can simply do:

(?:^|[^.,\d])(\d+)(?:[^.,\d]|$)
like image 188
Toto Avatar answered Oct 04 '22 23:10

Toto