正则表达式:查找整数而不是浮点数
regex: find integer but not float
我想要一个正则表达式模式来查找字符串中的任何整数,但不是浮点数(小数点为"."或",")。所以for string:
abc111.222dfg333hfg44.55
应该只找到:
333年我创建了regex模式:
(?<!\d[\.,]|\d)\d+(?![\.,]\d+|\d)
,但在c++ STL正则表达式中使用时失败。它抛出异常:
Unhandled exception at at 0x76AF4598 in xxxxxx.exe: Microsoft C++ exception: std::regex_error at memory location 0x00C1F218.
但是它在c# Regex类
中工作得很好更新:
我代码:smatch intMatch;
regex e1("(?<!\d[\.,]|\d)\d+(?![\.,]\d+|\d)");
string s("111.222dfg333hfg44.55");
regex_search ( s, intMatch, e1 );
但是会抛出异常:
regex e1("(?<!\d[\.,]|\d)\d+(?![\.,]\d+|\d)");
更新2:两个答案都是正确的,但对于c++ STL正则表达式Toto一个更好。
我不确定c++ STL,但许多正则表达式不支持可变长度负向后看。
在你的情况下,你可以简单地做:
(?:^|[^.,d])(d+)(?:[^.,d]|$)
由于不同语言/版本等使用的正则表达式风格可能存在许多差异。,我会尝试用基本的正则表达式函数来处理这个问题,大多数版本都支持,比如:
d+[,.]d+|(d+)
演示它只使用替代和组捕获,没有查找。整数被捕获到第一组
首先,您需要知道在像[]这样的一组字符中不应该转义元字符,因此您必须写[.,]
而不是[\.,]
。我试过下面的程序,它似乎找到了正确的匹配
std::string in = "abc111.222dfg333hfg44.55";
boost::regex re("(?<!(\d[.,]|.\d))\d+(?![.,\d])");
boost::sregex_iterator it(in.begin(), in.end(), re);
boost::sregex_iterator end;
for( ;it!=end; ++it)
{
boost::smatch s = *it;
std::cout << s[0] << std::endl;
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 为什么将两个浮点数相加会得到一个整数C++?
- 浮点数中整数的精确表示形式
- 浮点到整数转换出错(即使浮点数已经是整数)
- 将整数的二进制数据转换为浮点数
- 当我们C++将两个数组的整数除以 时,如何获得浮点数计算;
- C++整数除法到浮点数
- 整数浮点数除以自身是否保证为 1.f?
- 如何使用 c++ 模板实现整数、字符串、浮点数和日期对象的数组
- 根据浮点数选择最小整数类型
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 解析文本文件中的字符串、整数和浮点数
- 正则表达式浮点数和不带逗号的整数
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 结构中的整数、字符和浮点数
- 为什么我的函数返回一个整数,尽管我已经将答案指定为浮点数
- 给定一个整数 M,使得 (int)C < M 的最大浮点数 C 是多少?