正则表达式匹配字符串之间的数字 [英] Regex match digits between strings

查看:797
本文介绍了正则表达式匹配字符串之间的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从以下文本中提取整数值,介于字符串 start:和 end:之间,并且仅 之间。

I need to extract integer values from the following text, between strings "start:" and "end:", and only between.

 111222 garbage  999888 start:        123456       end:     start:         654321     end:

想要的结果:

123456
654321

这里是我所拥有的,但是我需要它来排除整数周围未知数量的空格。

Here is what I have, but I need it to exclude the unknown number of spaces around the integer.

std :: regex

std::regex

(?<=start:)(.*?)(?=end:)

RegExr

推荐答案

您可以使用

std::regex reg(R"(start:\s*(\d+)\s*end:)");

请参见 regex演示

它定义了 start:\s *(\d +)\ ends * end:匹配的正则表达式模式:start:,0 +个空格,然后捕获到组1中一个或多个数字,然后匹配0 +空格和 end:子字符串。

It defines the start:\s*(\d+)\s*end: regex pattern that matches start:, 0+ whitespaces, then captures into Group 1 one or more digits, and then matches 0+ whitespaces and end: substring.

请注意,如果您不能使用原始字符串文字( R(...) 表示法),您可以使用常规字符串文字定义模式,所有反斜杠都应加倍: start:\\s *(\\d +)\\s * end:

Note that in case you cannot use raw string literals (R"(...)" notation), you may define the pattern with a regular string literal where all backslashes should be doubled: "start:\\s*(\\d+)\\s*end:".

要获取所有匹配项,您需要 std :: sregex_token_iterator 并在获得匹配项时,请指定您需要获取所有第1组值:

To obtain all matches, you need std::sregex_token_iterator and when getting the matches, specify that you need to grab all Group 1 values:

const std::regex reg(R"(start:\s*(\d+)\s*end:)");
std::smatch match;
std::string s = "garbage 111222 garbage ... 999888 fewfew... start:        123456       end:     start:         654321     end:";
std::vector<std::string> results(std::sregex_token_iterator(s.begin(), s.end(), reg, 1),
                           std::sregex_token_iterator());

请参见在线C ++演示

如果 start内可以有任何值: end:,将 \d + 替换为。*?(匹配除换行符以外的任意0+个字符)。

If there can be any value inside start: and end:, replace \d+ with .*? (matching any 0+ chars other than line break characters).

这篇关于正则表达式匹配字符串之间的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆