C ++正则表达式允许用点分隔的数字

c++ regexp allowing digits separated by dot

本文关键字:分隔 数字 许用点 正则表达式      更新时间:2023-10-16

我需要 rexexp 允许在一行中最多用点分隔两位数字,例如 1.2 或 1.2.3 或 1.2.3.45 等,但不允许 1234 或 1.234 等。我正在尝试这个"^[\d{1,2}。+",但它允许所有数字。怎么了?

你可以试试这个:

^d{1,2}(.d{1,2})+$

正则表达式 101 演示

解释:

  1. 字符串的开头^
  2. d{1,2}后跟一位或两位数字
  3. 捕获组(开始
  4. .d{1,2}后跟一个点和一个或两个数字
  5. )捕获组的末尾
  6. +指示上一个捕获组重复 1 次或多次
  7. 字符串的末尾$

示例C++源(在此处运行(:

#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string regx = R"(^d{1,2}(.d{1,2})+$)";
string input = "1.2.346";
smatch matches;
if (regex_search(input, matches, regex(regx)))
{
cout<<"match found";
}
else
cout<<"No match found";
return 0;
}

我认为最后一个不应该超过 2 位数字。

(d{1,2}.)+d{1,2}(?=b)